当使用模板时,Constexpr 函数不是 constexpr

Constexpr function is not constexpr when template is used

本文关键字:函数 Constexpr constexpr      更新时间:2023-10-16

以下代码编译良好:

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;
}

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

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 函数'func'不能导致常量表达式"。

这怎么可能?

是的,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>{};
}