2

I'm wondering whether it's possible to implement an "interface"'s function via member function templates like so:

struct VisitorI
{
    virtual void Visit(int) = 0;
    virtual void Visit(float) = 0;
};

struct VisitorC : public VisitorI
{
    template<class T>
    void Visit(T) { /*Assume Visit(T) has syntatically the same implemenation for each relevant T */}
};


template void VisitorC::Visit(int);
template void VisitorC::Visit(float);


int main()
{
    VisitorC Visitor;

    return 0;
}

The above code doesn't compile because foo(int) and foo(float) are considered pure virtual in VisitorC, so I'm thinking it's not possible. I don't really see any particular reason why it shouldn't though...?

Cheers, Damian

YSC
  • 38,212
  • 9
  • 96
  • 149
Damian Birchler
  • 285
  • 1
  • 7
  • I guess that falls into the "virtual member function templates cannot be made virtual" category. Even though in this particular I think it wouldn't be too hard for the compiler to work it out. – Damian Birchler Mar 18 '16 at 09:11
  • related: http://stackoverflow.com/questions/2354210/can-a-member-function-template-be-virtual (in particular: the most upvoted answer) – YSC Mar 18 '16 at 09:12
  • @tobi303. Yes, you're right. I've corrected that. – Damian Birchler Mar 18 '16 at 09:22

1 Answers1

3

As a workaround, you could:

struct VisitorC : public VisitorI
{
    virtual void Visit(int a)   { Visit_impl(a); }
    virtual void Visit(float a) { Visit_impl(a); }
private:
    template<class T>
    void Visit_impl(T) { /* ... */ }
};
YSC
  • 38,212
  • 9
  • 96
  • 149