当使用模板时,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>{};
}
相关文章:
- 条件constexpr函数
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- constexpr构造函数需要常量成员函数时出现问题
- constexpr 函数获取常量字符*
- 如何在 constexpr 函数中实现回退运行时
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 在非 constexpr 函数中作为左值传递的变量上使用 'constexpr' 函数
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- NVCC 错误:string_view.h:constexpr 函数返回是非常量
- constexpr函数中的静态constexpr变量
- 在 constexpr funnction 中调用basic_string函数
- 为什么我的 constexpr 对象在我的函数中不是 constexpr?
- constexpr log10 整数函数
- C++:初始化 constexpr 构造函数中的成员数组
- 编译器生成的默认构造函数具有 constexpr 混淆行为
- 在 constexpr 构造函数中初始化数组是否合法?
- 在 constexpr 函数中断言
- MSVC 和函数参数的 constexpr?
- 具有位域的结构的 Constexpr 构造函数
- C++ 默认构造函数 constexpr 或正确未定义