How can I detect that a constuctor is really constexpr, so I can utilize static initialization?

橙三吉。 提交于 2019-12-02 06:11:51

If you are using Clang, use [[clang::require_constant_initialization]] on the variable. Otherwise, I don't know of a way.

The committee is looking at standardizing this as a keyword.

The only (current, toolchain-independent) way to prevent the compiler dropping the constexpr silently that I'm aware of, is to assign to a constexpr:

struct NonConstexpr {
    NonConstexpr() { }
};

template <typename T>
struct Bar {
    NonConstexpr nonConstexpr;

    constexpr Bar() { }
};

struct Foo {
    Bar<void> bar;

    constexpr Foo() { }
};

int main()
{
    constexpr auto f = Foo();
    return 0;
}

... will fail to compile with constexpr constructor calls non-constexpr function "Bar<T>::Bar() [with T=void]"

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!