2013-05-20 48 views
0

目标是创建一种“智能获取器”,从当前对象获取值(如果不存在),它会查找父对象中的值。包含依赖于类成员的模板的类

所以这ValueGetter类包含指向它包含在(得到它在构造函数运行时间参数)和成员指针操作它作为模板参数的对象。

这是最简单的例子:

template <class StyleType, int StyleType::*value> 
struct ValueGetter 
{ 
    ValueGetter(StyleType* containedIn); 
    int get(); 
    // Looks if the value is present in this style, 
    // if not it looks for the value in the parent style 
}; 

struct Style 
{ 
    Style *parent; 
    int a; 
    ValueGetter<Style, &Style::a> x; // Error: 'Style::a' : is not a type name, static, or enumerator 
}; 

当我将■类的范围之外,它编译。 通常,类可能包含依赖于类类型的模板,为什么这不起作用? 有没有其他方法可以解决这个问题,而不需要在运行时将构造器中的指针存储到构造函数中? (所以结构将包含每一个值额外的指针)

编辑:我刚刚成功地编译它在海湾合作委员会,但不是在MSVC(2012年),所以这是MSVC编译器错误?

+1

您正在使用什么编译器? –

+0

P.S .:你的代码片段[编译](http://ideone.com/R6xiba)在GCC 4.7.2 –

+0

在MSVC 2012中编译。 – kovarex

回答

1

我不认为指针(不要与指针类型混淆为T *)被允许在03 C++模板参数,只键入名称,整型常量或枚举常量。甚至没有float/double常量。这包括类成员指针。

更新: 而且静态非类型参数的工作原理:

template <class StyleType, int *value> 
struct ValueGetter 
{ 
    ValueGetter(StyleType* containedIn); 
    int get(); 
    // Looks if the value is present in this style, 
    // if not it looks for the value in the parent style 
}; 

struct Style 
{ 
    Style *parent; 
    static int a; 
    ValueGetter<Style, &Style::a> x; // Error: 'Style::a' : is not a type name, static, or enumerator 
};