matovitch
matovitch

Reputation: 1284

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.

Upvotes: 2

Views: 540

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

You can't do it directly, but you can use forwarders to have a common implementation:

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

Upvotes: 2

Yochai Timmer
Yochai Timmer

Reputation: 49251

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.

Upvotes: 3

Related Questions