[英]C++ function overload and initializer_list constructor
Here i have some code: 这里我有一些代码:
#include <string>
#include <iostream>
#include <initializer_list>
template <typename T>
class Test
{
public:
Test(std::initializer_list<T> l)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
Test(const Test<T>& copy)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
Test() = delete;
Test(Test&&) = delete;
};
void f(const Test<Test<std::string>>& x)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void f(const Test<std::string>& x)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
f({x});
}
int main()
{
Test<std::string> t1 {"lol"};
f(t1);
return 0;
}
The problem here is that i wanted to call overload void f(const Test<Test<std::string>>& x)
here: 这里的问题是我想在这里调用重载void f(const Test<Test<std::string>>& x)
:
f({x});
I know that if i call it like this: 我知道如果我这样称呼它:
f(Test<Test<std::string>>{x});
It will get the job done. 它将完成工作。
I just not quite understand what's happening in terms of compilation in the first case. 我只是不太了解第一种情况下的编译情况。
I thought that line f({x})
should: 我认为f({x})
应该:
Test<std::string>
. 创建临时对象Test<std::string>
。 Instead it just passes the same initial object over and over and none temporaries are created. 相反,它只是反复传递相同的初始对象,并且不会创建任何临时对象。 It's like just x
is the same as {x}
. 就像x
与{x}
。 Why compiler behave like that? 为什么编译器会那样表现?
My OS: 我的操作系统:
Linux Mint 19 Tara Linux Mint 19塔拉
Compiler: 编译器:
gcc 7.3.0 gcc 7.3.0
Compilation command: 编译命令:
g++ -std=c++11 -O0 test.cpp -o test -Wall -pedantic g ++ -std = c ++ 11 -O0 test.cpp -o test -Wall -pedantic
I thought that line f({x}) should: 我认为f({x})行应该:
- Create temporary object Test -创建临时对象测试
Your wrong, 你的失误,
{x}
build a const Test<std::string>&
from x
(identity). {x}
从x
(身份)构建const Test<std::string>&
。
As the 2 candidates are: 由于这两个候选人是:
void f(const Test<Test<std::string>>&)
#1 void f(const Test<Test<std::string>>&)
#1 void f(const Test<std::string>&)
#2 void f(const Test<std::string>&)
#2 overload_resolution are complicated, but currently, #2 is a better match (exact match). 重载解析很复杂,但是目前#2是更好的匹配(完全匹配)。
#1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.