1

I want to implement a generic method that could apply a determined operation on a struct member, passing that member as parameter. Something like this:

typedef struct Type_t{
    int a;
    double b;
} Type;

void gen_method(Type &t, TypeMember m){
    t.m += 1;
}

What I've done until now:

typedef struct Type_t{
    int a;
    double b;
} Type;

typedef double Type::* PointerToTypeMemberDouble;

void gen_method(Type &t, PointerToTypeMemberDouble member){
    t.*member += 1;
}

What I want to do

Now I want to implement the same generic method but using templates to allow the user to access any struct member, independentrly of its type. This is what I've tested:

typedef struct Type_t{
    int a;
    double b;
} Type;

template<typename T>
struct PointerToTypeMember{
    typedef T Type::* type;
};

template<typename T>
void gen_method(Type &t, PointerToTypeMember<T>::type member){
    // ...
}

The error

When I try to compile, I get this errors list: error C2061: syntax error : identifier 'type'

And this warning: warning C4346: 'myNamesPace::Type<T>::type' : dependent name is not a type

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
Dan
  • 2,135
  • 14
  • 39

2 Answers2

3

Firstly, for your error, you need to specify typename:

template<typename T>
void gen_method(Type &t, typename PointerToTypeMember<T>::type member) {

See Where and why do I have to put the “template” and “typename” keywords?

Secondly, you don't need the helper class template PointerToTypeMember at all. And because nested-name-specifier couldn't be deduced in template argument deduction, you have to specify the template argument when use it as:

Type t{};
gen_method<int>(t, &Type::a);
gen_method<double>(t, &Type::b);

You could specify the class member as the template parameter directly,

template<typename T>
void gen_method(Type &t, T Type::*member){
    t.*member += 1;
}

and no need to specify the template argument, template argument deduction will do it for you.

Type t{};
gen_method(t, &Type::a);
gen_method(t, &Type::b);
Community
  • 1
  • 1
songyuanyao
  • 163,662
  • 15
  • 289
  • 382
  • 2
    Note that your sample allows to deduce member type whereas OP has to specify the member type in `gen_method` call. – Jarod42 Apr 19 '16 at 08:17
0

I have found the problem.

template<typename T>
void gen_method(Type &t, typename PointerToTypeMember<T>::type member){
    // ...
}

The problem was that I have to tell the compiler that PointerToTypeMember<T>::type is a type using the typename keyword.

Dan
  • 2,135
  • 14
  • 39