【问题标题】:Class templates: restrict the template parameter类模板:限制模板参数
【发布时间】:2015-03-02 17:01:33
【问题描述】:

我可以决定编译器可以生成哪些类型的模板类吗?

假设我希望下一个类只能保存实数(浮点数、双精度数)而不是整数类型。

//can I force T to be only real number types?
template<typename T>
class RealNumber
{
public:
    T num;

    RealNumber() : num() {}

    void add(T x) { num += x; }
    T get() const { return num; }
};

所以这应该会产生一个编译错误:

RealNumber<int> myrealnumber;

【问题讨论】:

  • SFINAE with is_integral.
  • @LuchianGrigore:SFINAE 用于函数模板,用于控制重载解析。这需要static_assertis_floating_point

标签: c++ templates


【解决方案1】:

您可以断言该类型具有特定的特征:

#include <type_traits>

template<typename T>
class RealNumber
{
    static_assert(std::is_floating_point<T>::value, "Type must be floating point");

    // and so on
};

如果类型不合适,这将导致编译时错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2014-01-29
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多