【问题标题】:Restrict integer template parameter限制整数模板参数
【发布时间】:2012-05-13 08:23:27
【问题描述】:

我有这样的代码:

template<int N, typename T>
class XYZ {
public:
  enum { value = N };
  //...
}

有没有办法以某种方式限制 N?具体来说,我只想在 N 除以某个数字(例如 6)时才允许编译。 所以事实证明它不仅仅是一个类型限制。 首选方法是在没有 Boost 的情况下执行此操作。

【问题讨论】:

  • 仅供参考,Boost.MPL 已经包含 100% 的此类所需逻辑,因此您编写的任何代码都只是(可能很差)重复。

标签: c++ templates int restrictions


【解决方案1】:

一种 C++03 方法:

template<int X, int Y>
struct is_evenly_divisible
{
    static bool const value = !(X % Y);
};

template<int N, typename T, bool EnableB = is_evenly_divisible<N, 6>::value>
struct XYZ
{
    enum { value = N };
};

template<int N, typename T>
struct XYZ<N, T, false>; // undefined, causes linker error

对于 C++11,您可以避免一些样板并给出更好的错误消息:

template<int N, typename T>
struct XYZ
{
    static_assert(!(N % 6), "N must be evenly divisible by 6");
    enum { value = N };
};

【讨论】:

    【解决方案2】:

    我把它留在这里以备将来使用,因为在发布时我无法在网上找到一个很好的例子。

    使用概念的 C++20 方式:

    template<int X, int Y>
    concept is_evenly_divisible = X % Y == 0;
    
    template <int N, int M> requires is_evenly_divisible<N, M>
    struct XYZ
    {
        enum class something { value = N };
    };
    
    XYZ<12, 6> thing; // OK
    //XYZ<11, 6> thing; // Error
    

    甚至更短:

    template <int N, int M> requires (N % M == 0)
    struct XYZ
    {
        enum class something { value = N };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      相关资源
      最近更新 更多