c++ - 用户定义的文字作为可变参数模板

标签 c++ gcc c++11

GCC 4.7.2 似乎仅针对数字实现了可变字符模板化文字运算符:

template<char... chars>
constexpr size_t operator "" _size() { return sizeof...(chars); }

int main()
{
    std::cout << 42_size;    // (1) works
    std::cout << "foo"_size; // (2) does not
}
  • 是否有支持此代码的 GCC 版本?
  • (2) 是标准的一部分吗?

最佳答案

C++11标准2.14.8.5声明

If L is a user-defined-string-literal, let str be the literal without its ud-suffix and let len be the number of code units in str (i.e., its length excluding the terminating null character). The literal L is treated as a call of the form operator "" X (str, len)

因此将您的代码重写为:

#include <iostream>

// (1)
template<char... chars>
constexpr size_t operator "" _size() { return sizeof...(chars); }

// (2)
constexpr size_t operator "" _size( const char* str, size_t sz ) { return sz; }

int
main(void)
{
  std::cout << 42_size << std::endl;    // (1)
  std::cout << "foo"_size << std::endl; // (2)

  return 0;
}

明确指定 (2) 的正确形式

关于c++ - 用户定义的文字作为可变参数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14599754/

相关文章:

c++ - 平铺贴图 OpenGL C++

c++ - openCV中的掩蔽

c++ - 使用std::addressof(std::cout)而不是&std::cout有什么风险吗?

c++ - 如何最好地消除有关未使用变量的警告?

c++ - 如何返回 C++ 中递归函数被调用的次数?

c++ - 大型嵌入式公司真的是 "forced"使用旧的编程标准/编译器吗?

gcc - GCC LTO 是否执行跨文件死代码消除?

gcc - 是否可以同时安装 2 个不同版本的 GCC?

c++ - 使用 `std::function<void(...)>` 调用非 void 函数

c++ - 为什么编译器接受带有 long double 文字的 float 的初始化?