【问题标题】:Constexpr function is not constexpr when template is used使用模板时,constexpr 函数不是 constexpr
【发布时间】:2019-02-02 21:55:24
【问题描述】:

以下代码编译正常:

struct A {
    int i;
    constexpr A() : i(1) { }
    constexpr A(const A& that) : i(1) { }
};
constexpr auto func() {
    std::array<A, 3> result = {};
    return result;
}

但是,如果我们给A添加一个模板类型参数T

template<typename T> struct A {
    int i;
    constexpr A() : i(1) { }
    constexpr A(const A<T>& that) : i(1) { }
};
constexpr auto func() {
    std::array<A<int>, 3> result = {};
    return result;
}

编译器错误“constexpr function 'func' cannot result in an constant expression”。

这怎么可能?

【问题讨论】:

  • 哪个编译器?在Coliru 上,它编译得很好。
  • 编译器:Microsoft Visual C++ 14.16.27023

标签: c++ templates constexpr


【解决方案1】:

是的,MSVC 在实现 C++14/17 功能方面存在(或仍然存在)一些问题,这显然也适用于 constexpr。但是,对于 Visual Studio 2017 15.9,以下轻微修改对我有用(而 OP 中的版本也会出错):

template<typename T> struct A {
    int i;
    constexpr A() : i(1) { }
    constexpr A(const A<T>& that) : i(1) { }
};
constexpr auto func() {
    return std::array<A<int>, 3>{};
}

【讨论】:

  • 谢谢。这是 MSVC 编译器中的错误吗?
  • 是的,这是一个错误。这可能与复制构造函数或复制(-list)初始化有关。
猜你喜欢
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2011-09-15
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多