Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member template functions cannot be virtual - workaround?

I understand why member template functions cannot be virtual, but I'm not sure what the best workaround is.

I have some code similar to this:

struct Entity
{
    template<typename It>
    virtual It GetChildren(It it) { return it; }
};

struct Person : public Entity
{
    template<typename It>
    virtual It GetChildren(It it) { *it++ = "Joe"; }
};

struct Node : public Entity
{
    Node left, right;
    const char *GetName() { return "dummy"; }

    template<typename It>
    virtual It GetChildren(It it)
    {
        *it++ = left.GetName();
        *it++ = right.GetName();
        return it;
    }
};

Clearly, I need dynamic dispatch. But given that the classes are actually pretty large, I don't want to template the entire class. And I still want to support any kind of iterator.

What's the best way to achieve this?

like image 671
user541686 Avatar asked Nov 11 '11 20:11

user541686


People also ask

Can a member function template be virtual?

Member function templates can't be virtual functions. And, they can't override virtual functions from a base class when they're declared with the same name as a base class virtual function.

Can a non templated class have a templated member function?

A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.

Does function template support polymorphism?

Templates provide static/compile time polymorphism. While virtualism provides dynamic polymorphism.

What is virtual void in C++?

A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late binding on the function.


1 Answers

If supporting any kind of iterator is the only thing you want, you may use an iterator that uses type erasure. I think there is an any_iterator implemented somewhere in the Boost Sandbox/Vault or Adobe Labs or one of them. Here is the first result from Google:

http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/any_iterator.html

like image 148
K-ballo Avatar answered Nov 07 '22 17:11

K-ballo