当我击中不良的constexpr时,请停止Visual Studio 17编译



是否有任何方法可以强制编译器如果不应该击中constexpr?

下面的此代码比我更好地解释了这一切:

template<unsigned int number_base>
class arithmetic_type
{
    if constexpr(number_base == 0 || number_base == 1)
    {
        //hey, compiler! fail this compilation please
    }
    else
    {
        //go on with class implementation
    }
}

您想要static_assert()。在这种情况下,您可以删除if constexpr并直接断言:

template<unsigned int number_base>
class arithmetic_type
{
    static_assert(number_base != 0 && number_base != 1); // or >= 2, since unsigned
    //go on with class implementation
};

,但通常,您可能只需要static_assert(false)。但这是不明显的,这种断言总是会触发,因为这是一个非依赖性的条件。在这种情况下,您需要提供看起来依赖但实际上不是:

的东西
// always false, but could hypothetically be specialized to be true, but 
// nobody should ever do this
template <class T> struct always_false : std::false_type { };
static_assert(always_false<SomeDependentType>::value);

最新更新