2016-11-09 26 views
1

C++ 11只允许用户定义模板字串文本运营商,用下面的模板签名(taken from CppReference;返回类型并不需要是double):为什么这个模板签名不能像使用引号的字符串一样工作?

template <char...> double operator "" _x(); 

然而,看来这仅适用在数字形式,而不是引用的形式:

template <char... chs> 
std::string operator ""_r() 
{ 
    // ... construct some sort of string and return it 
} 

// ... 

auto my_str = "abc"_r; // ERROR (compiler messages copied below) 
auto my_num = 123_r; // NO ERROR 

GCC(5.1)或Clang(3.7)都不会给出有用的错误消息。 GCC说:

error: no matching function for call to ‘operator""_r()’ 
// printed source elided 
note: candidate: template<char ...chs> std::__cxx11::string operator""_r() 
// printed source elided 
note: template argument deduction/substitution failed: 
// ERROR OUTPUT ENDS HERE 
// (nothing is printed here, despite the ':' in the previous line) 

锵只是说:

error: no matching literal operator for call to 'operator "" _r' with arguments of types 'const char *' and 'unsigned long', and no matching literal operator template 

那么,为什么模板参数推导失败?为什么字面操作符模板不匹配?

而且,通常情况下,是否可以修复使用情况,以便文字操作符可以与非数字字符串一起使用?

回答

2

你不能声明一个接受可变参数字符组用户自定义字符串常量。这可能会在未来发生变化,但到目前为止,这就是它的一切。

,从同样的cppreference:

对于用户定义的字符串常量,所述用户定义的文字表达 被当作一个函数调用operator "" X (str, len),其中str是 字面而不UD-后缀和len为它不包括 终止空字符长度

+0

啊,我看 - 整数常量并且明确地说浮点文字被视为一个函数调用'运算符“” X <“C1”,“C2”,“C3 '...,'ck'>()'如果其他可能的文字操作符不可用。谢谢。 –

1

GCC有扩展允许

template <typename Char, Char...Cs> 
std::string operator ""_r() 
{ 
    // ... construct some sort of string and return it 
} 

Demo

+0

因为我确实尝试过使用GCC 5,所以我猜这在GCC 6中必须是新的? –

+0

根据[that](https://godbolt.org/g/036ejP),自gcc 4.9(但用C++ 14)。 – Jarod42

+0

噢,对,我用''代替''。 –

相关问题