相关疑难解决方法(0)

常量表达式中的模板化委托复制构造函数

这个问题的动机是这个。

考虑以下代码:

struct B {};

struct S {
    B b; // #1

    S() = default;

    template <typename ...dummy> // #2
    constexpr S(const S&) {}

    template <typename ...dummy> // #3
    constexpr S(S &other) 
        : S(const_cast<const S&>(other)) // #4
    {}
};

S s;
constexpr S f() {return s;}

int main() {
    constexpr auto x = f();
}
Run Code Online (Sandbox Code Playgroud)

GCC 成功编译了这段代码,但 Clang 拒绝了它(Godbolt.org 上的示例)。Clang 产生的错误信息是

<source>:21:20: error: constexpr variable 'x' must be initialized by a constant expression
    constexpr auto x …
Run Code Online (Sandbox Code Playgroud)

c++ templates copy-constructor language-lawyer constant-expression

6
推荐指数
1
解决办法
102
查看次数