我基本上有一个 std::integral_constant
的模拟版本包含一个变量,我想为这些派生自 Base<T>
的类专门化一个函数模板,像这样:
template<class T> struct Base{
typedef T type;
T t;
};
template<class T> struct A : Base<T>{
static constexpr T value = 1;
};
template<class T> struct B : Base<T>{
static constexpr T value = 2;
};
struct Unrelated{};
// etc.
template<class T> void foo(T t){
//I would like to specialize foo for A and B and have a version for other types
}
int main(){
foo(A<float>());//do something special based on value fields of A and B
foo(B<float>());
foo(Unrelated()); //do some default behavior
}
主要问题如下:
- 我不能包含
value
作为我期待的模板T = double
,float
,或其他一些非整数类型(否则我只是扩展std::integral_constant
) - 我不能干净地使用
std::is_base
因为我必须做std::is_base<Base<T::type>,T>
- 正在做
foo(Base<T>&)
不允许我看到value
而且我不想求助于虚拟value()
函数(或反射)。 - 显然,我想避免为每个派生类专门化 foo。
我认为答案在于使用 is_base
但无论我如何尝试使用它,我都无法让它工作。我缺少更简单的方法吗?
最佳答案
以下应该有效:
template<typename,typename = void>
struct IsBase
: std::false_type {};
template<typename T>
struct IsBase<T, typename std::enable_if<
std::is_base_of<Base<typename T::type>,T>::value
>::type>
: std::true_type {};
template<class T>
typename std::enable_if<IsBase<T>::value>::type foo(T t){
// use T::value
}
template<class T>
typename std::enable_if<!IsBase<T>::value>::type foo(T t){
// general case
}
关于c++ - 模板化派生类的特化函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21144203/