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/