use*_*920 5 c++ templates template-specialization c++11
我本质上有一个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
}
Run Code Online (Sandbox Code Playgroud)
以下是主要问题:
value作为模板,因为我期待T = double,float或一些其它的非整数类型(否则我只是延长std::integral_constant)std::is_base像我一样干净利用std::is_base<Base<T::type>,T> foo(Base<T>&)不会让我看到value,我不想诉诸虚拟value()功能(或反射).我认为答案在于使用,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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |