简体   繁体   中英

Recurring variadic template class parameters

I would like a variadic template class (with, say N template parameters) to define N member functions, each one taking a single parameter of type from the parameters list. I tried this :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) = 0;
};

template<class Derived>
class VtfVisitor
{
public:
    virtual void visit(Derived& derived) = 0;
};

Which does not work as I cannot redefine a template class. Then I tried solution proposed by Bo :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

Which still does not work: when trying this with VtfVisitor<D1,D2> , member function visit(D2&) is not defined in the instanciated template class (while visit(D1&) is well defined).

How could I get this to work as expected ?

Thanks for help.

You need to put the ellipsis outside the template argument list :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers>...
{
public:
    virtual void visit(Derived& derived) = 0;
};

As an example, if DerivedOthers... is {int, char, float} , you will get the following expansion:

class VtfVisitor : public VtfVisitor<char>, VtfVisitor<float>
{
public:
    virtual void visit(int& derived) = 0;
};

The compiler believes that you are redeclaring the same class with different number of parameters.

To create a specialization for the single argument case, you have to specify that after the class name:

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) = 0;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM