gpt4 book ai didi

c++ - 是否可以为字符串文字创建模板化的用户定义文字(文字后缀)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:01 24 4
gpt4 key购买 nike

当我发现可以将用户定义的文字模板化时,我感到很惊讶:

template <char ...C> std::string operator ""_s()
{
char arr[]{C...};
return arr;
}

// ...

std::cout << 123_s;

但上面的声明不适用于字符串文字:

"123"_s

给我以下错误:

prog.cpp: In function 'int main()':
prog.cpp:12:15: error: no matching function for call to 'operator""_s()'
std::cout << "123"_s;

prog.cpp:4:34: note: candidate: template std::string operator""_s()
template std::string operator ""_s()

prog.cpp:4:34: note: template argument deduction/substitution failed:

(Ideone)

有没有一种方法可以将模板化的用户定义文字与字符串文字一起使用?

最佳答案

Clang 和 GCC 支持允许你做的扩展

template<class CharT, CharT... Cs>
std::string operator ""_s() { return {Cs...}; }

但是标准C++中什么都没有;对此进行标准化的提案已多次提出并每次都被拒绝,最近一次是在不到一个月前,主要是因为模板参数包是一种确实表示字符串的低效方式。

关于c++ - 是否可以为字符串文字创建模板化的用户定义文字(文字后缀)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com