通过 constexpr 获取默认值

getting default value through constexpr

本文关键字:默认值 获取 constexpr 通过      更新时间:2023-10-16

请考虑以下代码:

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变量。