c++ - 模板化派生类的特化函数模板

标签 c++ templates c++11 template-specialization

我基本上有一个 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
}

Live example

关于c++ - 模板化派生类的特化函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21144203/

相关文章:

c++ - C++ 中的右值绑定(bind)混淆

c++ - 无法使用包装不同下一层的两个 ssl_stream 编译代码

c++ - 如何将返回 C++ 自定义类的函数与 Cython 连接?

c++ - 使用类模板需要模板参数列表,怎么办?

c++ - 用模板函数计算中值

c++ - std::async 超时

C++11 - 元组和移动语义

c++ - 重载运算符 >>

c++ - 同时具有聚合初始化和模板推导

c++ - 复制构造函数和转发构造函数之间的冲突