我想使用模板的递归来创建数组类型,如下面的代码块。 This is code dump on ideone。operator []为基于模板的O(1)复杂性阵列
实际上,我无法弄清楚如何为这种类型的数组创建O(1)复杂度的double& operator[](int)
和const double& operator[](int) const
。你有没有任何暗示如何在不改变主要意识形态的情况下做到这一点?它甚至有可能吗?
请帮忙。
#include <iostream>
#include <sstream>
using namespace std;
template <int N> struct Array : Array <N - 1>
{
double x;
template<int M> double& comp() { return Array<M>::x; }
template<int M> const double& comp() const { return Array<M>::x; }
//Prints vector
ostream& print(ostream& out) const
{
static_cast<const Array<N-1>*>(this)->print(out);
out << ", " <<x;
return out;
}
//Vector in place summation, without looping
Array& operator+=(const Array& v)
{
x+=v.x;
*static_cast<Array<N-1>*>(this) +=
static_cast<const Array<N-1>&>(v);
return *this;
}
};
template <> struct Array<1>
{
double x;
template<int M> double& comp() { return Array<M>::x; }
template<int M> const double& comp() const { return Array<M>::x; }
//Prints vector
ostream& print(ostream& out) const
{
out << x;
return out;
}
//Vector in place summation, without looping
Array& operator+=(const Array& v)
{
x+=v.x;
return *this;
}
};
template<int N>
ostream& operator<<(ostream& out, const Array<N>& v)
{
out << "("; v.print(out); out << ")";
return out;
}
int main()
{
Array<3> vec;
//Here I want to do something like: vec[0] = 1; vec[1] = 2; vec[3] = 3;
//instead of what you see
vec.comp<1>() = 1; vec.comp<2>() = 2; vec.comp<3>() = 3;
cout << vec << endl;
cout << (vec+=vec) << endl;
return 0;
}
UPDATE1
你怎么看待这个thing什么:
double& operator[] (int i) {
return reinterpret_cast<double*>(this)[i];
}
?而且,如果可以用不那么棘手的方式来完成,我还是会徘徊。
UPDATE2
OK!在@SergV输入之后,我决定,最好的方法是使用开关,因为它看起来不像reinterpret_cast
那么棘手,并且可能会给O(1)复杂性带来些许希望。非常感谢@SergV提供了大量新信息。对我来说是新的,因为。
UPDATE3
Why not to do your own jump table?
当它是必要的递归,才应使用。如果你转储递归,你可以简单地把'double x;'改成'double x [N];'一切都会简单得多。 –
同意。但是,如果可以在这里执行操作符[],它仍然很有趣。我的意思是理论上的。 –
是的,它可以做到。粗略地说:'return'index == 0? x:'static_cast *>(this).operator [](index - 1);'。未经测试。 –