2016-11-09 28 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

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

相關問題