【发布时间】: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";
}
};
如何调用基类的模板函数?
【问题讨论】:
-
您能否使用更准确的术语。当它是类模板而不是定义的类时,就像“类模板”而不是“类”?提前谢谢。
-
为什么
set和get是模板化的?你真的写到他们的类型必须是T
标签: c++ templates inheritance