0

The goal is to make kind of "smart getter" that gets the value from the current object if it is present, if not, it looks for the value in the parent object.

So this ValueGetter class contains pointer to the object it is contained in (gets it as run time parameter in constructor) and pointer to member it operates on as template parameter.

This is the most simple example:

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
};

When I move the x outside of the scope of the class, it compiles. Generally it is possible for class to contain template dependent on the class type, so why this doesn't work? Is there any other way to solve this issue without storing the pointer to member in runtime in constructor? (So the structure would contain extra pointer for every value)

Edit: I just succesfully compiled it in GCC, but not in MSVC (2012), so is this MSVC compiler error?

4

1 回答 1

1

我不认为指针(不要与 T* 中的指针类型混淆)在 03 C++ 中被允许作为模板参数,只允许类型名称、整数常量或枚举常量。甚至没有浮点/双精度常量。这包括类成员指针。

更新:此外,静态非类型参数有效:

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
};
于 2013-05-20T17:24:52.027 回答