Search code examples
c++templatesc++11pure-virtual

Use templates to generate pure virtual base class methods


That may sound kind of strange, and I may have to refactor my code at some point but I would need to generate the pure virtual base class methods with a template function. Is it doable with C++11 (variadic templates ?) ?

Example :

struct I
{
    virtual void foo(int) = 0;
    virtual void foo(float) = 0;
};

struct S : public I
{
    template<typename T>
    void foo(T t) { /*do the same symbolic stuff on t*/ } 
};

int main()
{
    S s;
    s.foo(0);
    s.foo(0.0f);
    return 0;
}

Giving the following error (clang) :

main.cpp:65:7: error: variable type 'S' is an abstract class
    S s;
      ^
main.cpp:53:18: note: unimplemented pure virtual method 'foo' in 'S'
    virtual void foo(int) = 0;
                 ^
main.cpp:54:18: note: unimplemented pure virtual method 'foo' in 'S'
    virtual void foo(float) = 0;
                 ^
1 error generated.

Solution

  • You can't do that.

    A signature of a template method is not the same of a non-template method.

    And you can't have a virtual template method.