模板基类

时间:2017-05-15 07:21:52

标签: c++ templates inheritance

我有以下情况:

一个可变参数模板类,它继承“自身”来解析可变参数模板参数。可变参数模板类有两个模板方法。在这些方法中,我想调用基本模板类模板方法。对于set方法,它似乎有效。

template<class T, class ... R>
class ValueProvider : ValueProvider<R...>{
    public:

        T value;
        const std::type_info& type = typeid(T);

        ValueProvider()
        {}

        template<class G>
        inline G get(){
            if(this->type.hash_code() == typeid(G).hash_code())
                return this->value;
            else{
                //----- interesting part -----
                return ValueProvider<R...>::get<G>();        /*<- compile ERROR: expected primary-expression before ‘>’ token*/
                return ValueProvider<R...>::get();        /*<- compile ERROR: no matching function for call to ‘ValueProvider<int, char>::get()’*/
                return ValueProvider::get<G>();        /*<- runtime ERROR (infinit recursion)*/
            }
        }

        template<class G>
        void set(G p){
            if(this->type.hash_code() == typeid(G).hash_code())
                this->value = p;
            else
                ValueProvider<R...>::set(p);
        }
};

template<class T>
class ValueProvider<T>{
    public:
        T value;
        const std::type_info& type = typeid(T);

        ValueProvider()
        {}

        template<class G>
        inline G get(){
            if(this->type.hash_code() == typeid(G).hash_code())
                return this->value;
            throw "fail";
        }

        template<class G>
        void set(G p){
            if(this->type.hash_code() == typeid(G).hash_code())
                this->value = p;
            else
                throw "fail";
        }
};

如何调用基类的模板函数?

1 个答案:

答案 0 :(得分:2)

通常的依赖名称问题:由于ValueProvider<R...>取决于R,您必须消除该范围中get是模板的歧义:

return ValueProvider<R...>::template get<G>();