一组模板结构

时间:2012-10-07 15:34:23

标签: c++ templates struct

我有来自Base结构的int模板化的结构。

struct Base { int i; double d; }; 
template< int N > struct Derv : base { static const int mN = N; };

我需要制作一个Derv&lt; N>其中N可以根据该数组中的每个结构而变化。我知道C / C ++不允许不同类型的对象数组,但有没有办法解决这个问题呢?我正在考虑以某种方式分离类型信息(暗示像Base结构的指针或联合弹簧的使用到我的脑海中,但是所有这些我都不知道如何存储每个数组元素的类型信息以供使用DURING编制时间)。如您所见,每个Derv的内存模式&lt; N>是一样的。

我需要在我的代码中稍后访问每个数组元素的类型以进行模板特化。这一切的总体目标是拥有一个编译时调度机制,而无需进行运行时&#34;类型切换&#34;代码中的某个地方。

2 个答案:

答案 0 :(得分:1)

我猜你可以使用ptr = dynamic_cast<Type>(element); .. ptr等于NULL如果它是错误的类型。 例如:

#include <map>
#include <cmath>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iostream>


using namespace std;

struct Base { int i; double d; Base(){}; virtual ~Base(){};}; 
template< int N > struct Derv : public Base { static const int mN = N; ~Derv(){}; };

int main(int argc, char **argv){
    Base* arr[2];
    arr[0] = new Derv<10>;
    arr[1] = new Derv<5>;
    Derv<10> *ptr = dynamic_cast<Derv<10>* >(arr[0]);
    Derv<5> *ptr2 = dynamic_cast<Derv<5>* >(arr[0]);
    cout << ptr << endl << ptr2 << endl;
    return 0;
}
// That should print 
0x9571008 //ptr to object will differ every time.
0 // Null because of wrong type.

但是你需要在结构中定义虚拟析构函数,以便它可以工作,和/或虚函数。

答案 1 :(得分:1)

这当然是不可能的。如果你做了

int i;
std::cin >> i;
some_magic_array X[size];

那么X[i]的类型是什么?哦,等等,你不可能知道。这不是C ++特有的,它基本上是不可能的。这就是为什么不存在some_magic_array允许这样做的原因。

除非您有效使用std::tuple并保证i是constexpr。然后你绝对可以用std::get<i>(tup);

来做到这一点