What is C++20#39;s string literal operator template?(C++的字符串文字运算符模板是什么?)
问题描述
什么是C++20的字符串文字运算符模板?在这方面,CpPreferences的example相当简明,我不是很清楚:struct A { A(const char *); auto operator<=>(const A&) const = default; };
template<A a> A operator ""_a();
在尝试理解此功能时,我刚刚了解到在C++中可以使用数值文字运算符模板,它使数值常量的每一位都作为非类型参数传递给模板(参见。更好的解释here)。目前,文字运算符模板不能处理字符文字,尽管有支持这一功能的编译器扩展。我不认为C++20的字符串模板与此有任何关系,因为我了解到,扩展文本运算符模板以使用字符文字的提议在委员会中被否决了?
有两个独立的提案: 第一个提案被部分并入第二个提案。作为非类型模板参数,字符串文本仍然不是有效参数,但它们是类类型中的有效参数。[temp.arg.nontype]/4中的示例可能会有所帮助: 然而,第一个方案中扩展文字运算符的部分被合并到第二个方案[lex.ext]/5:推荐答案
template<class T, T p> class X {
/* ... */
};
X<const char*, "Studebaker"> x; // error: string literal as template-argument
const char p[] = "Vivisectionist";
X<const char*, p> y; // OK
struct A {
constexpr A(const char*) {}
friend auto operator<=>(const A&, const A&) = default;
};
X<A, "Pyrophoricity"> z; // OK, string literal is a constructor argument to A
如果S包含带有非类型模板参数的文字运算符模板,且字符串是格式良好的模板参数,则文字L被视为以下形式的调用
operator "" X<str>()
所以使用这个:
struct A { A(const char *); auto operator<=>(const A&) const = default; };
template<A a> A operator ""_a() { return a; }
我们可以编写"Hello"_a
,这将被解释为调用operator "" _a<A("Hello")>
。
请注意,这些规则略有变化,因为根据P1185,默认的<=>
要求将更改为默认的==
要求。
这篇关于C++的字符串文字运算符模板是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++的字符串文字运算符模板是什么?


- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01