C++ 为什么内联对象不是constexpr?

C++ 为什么内联对象不是constexpr?,c++,c++11,constexpr,C++,C++11,Constexpr,使用constexpr断言函数,如果对象是constexpr,则无法在生成时编译它们 但是,对于内联对象,断言是在运行时而不是构建时触发的(请参见下面的代码) 在main函数中,无法编译第一个对象(如预期)。 编译第二个对象,但在运行时中止执行(如预期)。 但是第三个对象是编译的,而编译器不应该允许它 这意味着内联对象不是constexpr? 在这种情况下,有没有办法使内联对象成为constexpr #include <cassert> #include <utility>

使用constexpr断言函数,如果对象是constexpr,则无法在生成时编译它们

但是,对于内联对象,断言是在运行时而不是构建时触发的(请参见下面的代码)

在main函数中,无法编译第一个对象(如预期)。
编译第二个对象,但在运行时中止执行(如预期)。
但是第三个对象是编译的,而编译器不应该允许它

这意味着内联对象不是constexpr?
在这种情况下,有没有办法使内联对象成为constexpr

#include <cassert>
#include <utility>

// constexpr assert. Sources:
// https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/
// https://gist.github.com/oliora/928424f7675d58fadf49c70fdba70d2f

template<class Assert>
void _constexpr_assert_failed(Assert&& a) noexcept
{
    std::forward<Assert>(a)();
}

// When evaluated at compile time emits a compilation error if condition is not true.
// Invokes the standard assert at run time.
#define FOO_ASSERT(cond) \
        ((void)((cond) ? 0 : (_constexpr_assert_failed([](){ assert(! bool(#cond)); }), 0)))

template<typename Type>
constexpr const Type& assertRange(const Type& value, const Type& minimum, const Type& maximum) noexcept
{
    return FOO_ASSERT(value >= minimum && value <= maximum),
           value;
}

struct Color
{
    float r;
    float g;
    float b;

    constexpr Color(float r, float g, float b) noexcept :
        r(assertRange(r, 0.0f, 1.0f)),
        g(assertRange(g, 0.0f, 1.0f)),
        b(assertRange(b, 0.0f, 1.0f))
    {
    }
};

Color foo(const Color& color)
{
    return Color(color.r * 0.5f, color.g * 0.5f, color.b * 0.5f);
}

int main()
{
    // Build time error:
    // constexpr Color constexprBadColor(10, 0, 0);

    // Run time error:
    // Color runtimeBadColor(10, 0, 0);

    // Run time error?
    foo(Color(10, 0, 0));

    return 0;
}
#包括
#包括
//constexpr断言。资料来源:
// https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/
// https://gist.github.com/oliora/928424f7675d58fadf49c70fdba70d2f
模板
void\u constexpr\u assert\u失败(assert&&a)无异常
{
标准:转发(a)();
}
//在编译时求值时,如果条件不为true,则会发出编译错误。
//在运行时调用标准断言。
#定义FOO_断言(cond)\
((void)((cond)?0:(_constexpr_assert_失败([](){assert(!bool(#cond));}),0)))
模板
constexpr const Type&assertRange(const Type&value、const Type&minimum、const Type&maximum)无例外
{

返回FOO_断言(value>=minimum&&value What object,
foo
?根据您的说法,什么是内联对象?不太可能在编译时添加。当前正在发生什么?您希望发生什么?在您的问题中如何证明这一点?
constepr
仅用于所需的const表达式。为什么您认为它不是constexpr?我已经重写了这个问题。什么对象,
foo
?根据您的说法,什么是内联对象?不太可能在编译时添加。目前正在发生什么?您期望发生什么?如何在您的问题中证明这一点?
constepr
仅用于所需的const表达式。为什么您认为它是n康斯特普勒吗?我已经重写了这个问题。