Search code examples
c++templates

Is there a way to force the instantiation of a member function for every template instanciation?


Given the following code, I would like to have the AST for foo<int>::bar:

// foo.cpp
template <typename T>
struct foo {
    const char *bar() { /* Implementation depending on T. */ }
};

int main() {
    foo<int> f;
}

Is there a way to force the instantiation of the member function bar ? Indeed it is absent from the output of clang++ -Xclang -ast-dump foo.cpp.

I could add template const char* foo<int>::bar(); at namespace scope, but I would have to do it once for every template instance, and I don't want to do that.


Solution

  • Making the method virtual would force instiation of that method with the class Demo

    To avoid drawback of virtual, you might dummy Odr-use it in constructor:

    struct foo {
        foo() { static_cast<void>(&foo::bar); }
        const char *bar() { /* Implementation depending on T. */ }
    };
    

    So each implementation of the constructor would implicitly instantiate the given method.

    Demo