通过 constexpr 获取默认值
getting default value through constexpr
请考虑以下代码:
template<typename T>
constexpr T getDefault()
{
if constexpr (std::is_same_v<T, CString>)
{
return "";
}
}
template<typename T>
struct getdef
{
static constexpr T value = getDefault<T>();
};
现在我想获取CString的默认值...CString 是 MFC 的类。
CString s2 = getDefault<CString>();
CString s = getdef<CString>::value;
使用 getDefault 的第一行正确编译,但第二行发出错误。
错误 C2127 "值":非法初始化"constexpr"实体 非常量表达式
我在这里做错了什么?
CString
没有constexpr
构造函数,因此它不能用于初始化constexpr
对象。
错误很明显;由于 CString
等类没有constexpr
构造函数,因此它们不能实例化为constexpr
变量。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 具有默认值的引用获取函数
- 当给定默认值时,为什么此模板参数推导失败
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 格式化浮点值:返回默认值
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray
- 如何将数组部分初始化为某个默认值?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 创建一个包含 c++ 默认值的环境文件
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- Makefile g++ 使用命令行中的 -D 变量进行编译,默认值
- Switch 语句(字符串)一直选择默认值,除非其为零
- 如何使用默认值将枚举声明为 extern
- 从指针访问值或获取其默认值(如果为 null)的最干净方法
- 通过 constexpr 获取默认值
- 设置公共指数 e 的默认值,并获取 n 作为键对的模数
- 如何获取任何类型的默认值
- 布尔数组获取意外的默认值
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- c++在不创建新对象的情况下获取类成员的默认值