我们可以只为某些数据类型定义模板函数吗?

der*_*khh 6 c++ templates

可能重复:
仅接受某些类型的C++模板

例如,如果我们想要定义一个模板函数,我们可以使用整数,浮点数,双精度数而不是字符串.有一个简单的方法吗?

Die*_*ühl 9

这样做的方式std::enable_if是以某种形状或形式使用.然后将支持类型的选择器用作返回类型.例如:

  template <typename T> struct is_supported { enum { value = false }; };
  template <> struct is_supported<int> { enum { value = true }; };
  template <> struct is_supported<float> { enum { value = true }; };
  template <> struct is_supported<double> { enum { value = true }; };

  template <typename T>
  typename std::enable_if<is_supported<T>::value, T>::type
  restricted_template(T const& value) {
    return value;
  }
Run Code Online (Sandbox Code Playgroud)

显然,你想给这些特征一个更好的名字is_supported.std::enable_if是C++ 2011的一部分,但如果您使用的标准库不可用,它很容易实现或从boost获得.

通常,由于模板实现通常具有隐式限制,因此通常不必强加显式限制.但是,有时禁用或启用某些类型会很有帮助.