- 論壇徽章:
- 1
|
我有個(gè)小例子:
- #include<utility>
- using namespace std;
- struct A{
- int i;
- char c;
- };
- void f(const A&){}
- template<class T>
- void g(T&& t)
- {
- f(forward<T>(t));
- }
- int main() {
- A a={1,'@'};//OK
- f({1,'#'});//OK
- g({1,'@'});//Compilation error
- return 0;
- }
復(fù)制代碼
上面的代碼中,{1,'@'}本身是個(gè)初始化語(yǔ)義,`A a={1,'@'};`,編譯器判定表達(dá)式右邊的{}是一個(gè)std::initializer_list嗎?? 它會(huì)自動(dòng)轉(zhuǎn)化成為A類(lèi)型? 對(duì)于f而言也是如此嗎
問(wèn)題是: 對(duì)于模板函數(shù)g()而言,傳入?yún)?shù){1,'@'}類(lèi)型不被識(shí)別,clang編譯錯(cuò)誤如下:
- testArray.cpp:16:5: error: no matching function for call to 'g'
- g({1,'@'});//fix: g<A>({1,'@'})
- ^
- testArray.cpp:9:6: note: candidate template ignored: couldn't infer
- template argument 'T'
- void g(T&& t)
- ^
復(fù)制代碼
這是為什么?
|
|