Question

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?

Was it helpful?

Solution

I don't think pointers (not to confuse with pointer types as in T*) are allowed as template parameters in 03 C++, only type names, integral constants or enum constants. Not even float/double constants. That includes class member pointers.

Update: Also, static non-type parameters work:

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
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top