限制整数模板参数

Igo*_*ack 2 c++ int templates restrictions

我有一个像这样的代码:

template<int N, typename T>
class XYZ {
public:
  enum { value = N };
  //...
}
Run Code Online (Sandbox Code Playgroud)

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

ild*_*arn 5

一个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
Run Code Online (Sandbox Code Playgroud)

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

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