Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Address of templated member function [duplicate]

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;


like image 592
Allan Avatar asked Mar 22 '23 18:03


2 Answers

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>;
like image 125
Casey Avatar answered Apr 26 '23 12:04


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.

like image 30
Michael Avatar answered Apr 26 '23 13:04