- 论坛徽章:
- 1
|
我有个小例子:
- #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;
- }
复制代码
上面的代码中,{1,'@'}本身是个初始化语义,`A a={1,'@'};`,编译器判定表达式右边的{}是一个std::initializer_list吗?? 它会自动转化成为A类型? 对于f而言也是如此吗
问题是: 对于模板函数g()而言,传入参数{1,'@'}类型不被识别,clang编译错误如下:
- 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)
- ^
复制代码
这是为什么?
|
|