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

时间:2011-12-29 18:07:36

标签: c++ templates

  

可能重复:
  C++ templates that accept only certain types

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

3 个答案:

答案 0 :(得分: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;
  }

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

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

答案 1 :(得分:0)

您可以检查值的类型。如果它们是您指定的类型之一,您可以继续,如果不是,您可以返回该功能。 有关详细信息,请参阅此处:http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fthe_typeid_operator.htm

使用typeid你也应该能够抛出一个compileerror。

答案 2 :(得分:0)

通常将某些类型列入白名单会严格限制模板的使用。

Boost所谓的concepts基本上是模板的接口。 如果不满足某些条件(缺少函数或使用错误的参数等),则可以创建编译时错误,而不是将某些类型列入白名单。当然,您也可以使用它将模板参数限制为某些类型。