【问题标题】:C++ calling template method of template base classC++调用模板基类的模板方法
【发布时间】:2017-05-15 07:21:51
【问题描述】:

我有以下场景:

一个可变参数模板类,它继承“自身”来解析可变参数模板参数。可变参数模板类有两个模板方法。在这些方法中,我想调用基本模板类模板方法。对于 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";
        }
};

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

【问题讨论】:

  • 您能否使用更准确的术语。当它是类模板而不是定义的类时,就像“类模板”而不是“类”?提前谢谢。
  • 为什么setget 是模板化的?你真的写到他们的类型必须是T

标签: c++ templates inheritance


【解决方案1】:

通常的从属名称问题:由于ValueProvider&lt;R...&gt; 依赖于R,您必须消除该范围内的get 是一个模板的歧义:

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

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 2016-08-17
    • 2012-02-04
    • 1970-01-01
    • 2014-06-19
    • 2014-03-22
    • 2011-05-18
    • 1970-01-01
    • 2012-03-06
    相关资源
    最近更新 更多