相关疑难解决方法(0)

这是一个错误吗?Constexpr构造函数默默地变为非constexpr

看看这段代码:

struct NonConstexpr {
    NonConstexpr() { }
};

template <typename T>
struct Bar {
    NonConstexpr nonConstexpr;

    constexpr Bar() { }
};

struct Foo {
    Bar<void> bar;

    constexpr Foo() { }
};
Run Code Online (Sandbox Code Playgroud)

Foo有一个成员,Foo::bar::nonConstexpr有一个非constexpr构造函数.所以,我的期望是这不应该编译.但它与gcc,clang和msvc编译.这是编译器错误,还是某些规则允许编译此代码?

如果我直接添加NonConstexpr成员Foo,代码将不再编译.

(我遇到了这个问题,因为我期望全局Foo对象的静态初始化,但它被动态初始化,并且由于"静态初始化命令惨败"而导致问题)

c++ language-lawyer c++17

17
推荐指数
1
解决办法
429
查看次数

Constexpr成员函数

假设我有一个由引擎参数化的struct模板S

template<class Engine> struct S;
Run Code Online (Sandbox Code Playgroud)

我有两个引擎:具有constexpr成员函数的“静态”引擎size()和具有非constexpr成员函数的“动态” 引擎size()

struct Static_engine {
    static constexpr std::size_t size() {
        return 11;
    }
};

struct Dynamic_engine {
    std::size_t size() const {
        return size_;
    }
    std::size_t size_ = 22;
};
Run Code Online (Sandbox Code Playgroud)

我想定义size()的成员函数S可以被用作constexpr如果发动机是size()constexpr。我写:

template<class Engine>
struct S {
    constexpr std::size_t size() const {
        return engine_.size();
    }
    Engine engine_;
};
Run Code Online (Sandbox Code Playgroud)

然后,以下代码将与GCC,Clang,MSVC和ICC一起编译:

S<Static_engine> sta;         // not constexpr
S<Dynamic_engine> …
Run Code Online (Sandbox Code Playgroud)

c++ constexpr c++17 c++20

4
推荐指数
1
解决办法
127
查看次数

为什么模板允许constexpr函数成员使用非constexpr构造函数?

使用C++ 14.为什么这会编译:

template<unsigned N>
constexpr bool foo()
{
    std::array<char, N> arr;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

但不是吗?

constexpr bool foo()
{
    std::array<char, 10> arr; // Non-constexpr constructor 'array' cannot be used in a constant expression
    return true;
}
Run Code Online (Sandbox Code Playgroud)

c++ templates constexpr c++14

2
推荐指数
1
解决办法
464
查看次数

标签 统计

c++ ×3

c++17 ×2

constexpr ×2

c++14 ×1

c++20 ×1

language-lawyer ×1

templates ×1