【问题标题】:What is C++20's string literal operator template?什么是 C++20 的字符串文字运算符模板?
【发布时间】:2019-06-14 03:33:53
【问题描述】:

什么是 C++20 的字符串文字运算符模板? Cppreference 的example 在这方面非常简洁,对我来说不是很清楚:

struct A { A(const char *); auto operator<=>(const A&) const = default; };

template<A a> A operator ""_a(); 

在尝试了解此功能是什么时,我刚刚了解到您可以在 C++ 中使用 数字文字运算符模板,这使得数字常量的每个数字都作为非类型参数传递给一个模板(参见更好的解释here)。目前,文字运算符模板不适用于字符文字,尽管有编译器扩展支持它。我不认为 C++20 的 string 文字运算符模板与此有任何关系,因为我了解到扩展文字运算符模板以使用字符文字的提议被委员会否决了?

【问题讨论】:

  • the proposal 回答你的问题了吗?
  • @LightnessRacesinOrbit 那是被否决的版本。
  • 好的,this one 怎么样?

标签: c++ c++20 user-defined-literals


【解决方案1】:

有两个单独的提案:

  • 允许字符串文字作为非类型模板参数 (P0424)
  • 允许类类型作为非类型模板参数 (P0732)

第一个提案被部分合并到第二个提案中。字符串文字仍然不是作为非类型模板参数的有效参数,但它们是类类型的有效参数。 [temp.arg.nontype]/4 的示例可能会有所帮助:

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

但是,第一个提案中扩展文字运算符的部分被合并到第二个提案中,[lex.ext]/5

如果 S 包含带有非类型模板参数的文字运算符模板,其中 str 是格式良好的模板参数,则文字 L 被视为形式的调用 operator "" X&lt;str&gt;()

所以使用这个:

struct A { A(const char *); auto operator<=>(const A&) const = default; };     
template<A a> A operator ""_a() { return a; }

我们可以写"Hello"_a,会被解释为调用operator "" _a&lt;A("Hello")&gt;


请注意,这些规则略有变化,因为默认的&lt;=&gt; 要求将根据P1185 更改为默认的== 要求。

【讨论】:

    猜你喜欢
    • 2017-02-09
    • 1970-01-01
    • 2016-06-08
    • 2010-09-21
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多