c ++中的依赖类型,非零类型

She*_*she 5 c++ types

让我们说这是一个非零能力类型的裸骨.

template<typename T>
struct NonZero {
    T val;
};
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否可以创建一个构造函数NonZero,以获取文字类型T并静态检查它是否为非零,然后将其分配给val.

NonZero<int> n( 0 ); // compilation error
NonZero<int> n( 1 ); // ok
Run Code Online (Sandbox Code Playgroud)

或者有没有更好的方法来实现非零类型?

ale*_*in0 5

由于该值在编译时已知,因此您可以将其设为模板参数并使用std::enable_if:

template<typename T, T x>
struct NonZero {
    const static std::enable_if_t<x != T(0), T> value = x;
};
Run Code Online (Sandbox Code Playgroud)

用法:

int x = NonZero<int, 1>::value; // OK
int x2 = NonZero<int, 0>::value;// Compilation error
Run Code Online (Sandbox Code Playgroud)


ale*_*in0 3

另一种选择是检查constexpr构造函数中的值是否为零:

template<typename T>
struct NonZero {
    const T value;
    constexpr NonZero(const T val) :
        value(val != 0 ? val : throw std::runtime_error("should be non-zero"))
    {}
};
Run Code Online (Sandbox Code Playgroud)

用法:

NonZero<int> v(1);            // OK
NonZero<int> v2(0);           // Compiles OK, but throws in run-time
constexpr NonZero<int> v3(1); // OK
constexpr NonZero<int> v4(0); // Compilation error
Run Code Online (Sandbox Code Playgroud)

这种方法只适用于constexpr变量,但看起来更简单。

此外,您可以使用函数或用户定义的文字,而不是使用structwith构造函数,其思想完全相同。constexprconstexpr

  • 我太愚蠢了,别介意我的评论,当然,当用 0 构造变量时会出现编译错误。无论如何,谢谢你,这正是我想要的。 (2认同)