使用模板时constexpr函数不是constexpr
Constexpr function is not constexpr when template is used
以下代码可以正常编译:
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;
}
但是,如果我们将模板类型参数T
添加到A
,
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>{};
}
以下代码可以正常编译:
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;
}
但是,如果我们将模板类型参数T
添加到A
,
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>{};
}