5

In the example below, how do I find the address of the member function f

template<typename HANDLER>
void serialize(HANDLER &h) {
    //  Compiler error (gcc 4.8.1)
    //  test.cxx: In function ‘void serialize(HANDLER&)’:
    //  test.cxx:9:26: error: expected primary-expression before ‘int’
    //       auto x = &HANDLER::f<int>;
    //                            ^
    //  test.cxx:9:26: error: expected ‘,’ or ‘;’ before ‘int’
    auto x = &HANDLER::f<int>;
}

struct HandlerA {
    template<typename T> void f() { }
};

struct HandlerB {
    template<typename T> void f() { }
};

struct HandlerC {
    template<typename T> void f() { }
};

int main() {
    HandlerA a;
    HandlerB b;
    HandlerC c;

    a.f<int>();
    b.f<int>();
    c.f<int>();

    serialize(a);
    serialize(b);
    serialize(c);
}
Allan
  • 4,562
  • 8
  • 38
  • 59

2 Answers2

8

You need to tell the compiler that f is a template so that it can parse the function correctly:

auto x = &HANDLER::template f<int>;
Casey
  • 41,449
  • 7
  • 95
  • 125
1

Casey is correct.

A template, before instantiation has no address. as the template is used (instantiated) with specific parameters, a unique function in memory is created.

You can use/create a real function with any type: int, char, float, double, classXYZ... there's no limit to how many pointers to that function there could be.

Michael
  • 2,118
  • 1
  • 19
  • 25