4

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,390
  • 7
  • 36
  • 55

2 Answers2

7

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
  • 40,083
  • 7
  • 88
  • 120
0

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
  • 1,888
  • 1
  • 17
  • 24