首先 - 这段代码很糟糕,我知道,它是用于试验模板的,但我真的不知道它是如何/为什么它的工作原样.
代码:
#include <iostream>
#include <vector>
#include <string>
template <typename T>
class Container {
public:
Container() {
std::cout << "Container()" << std::endl;
}
Container(const Container& other){
std::cout << "Container(const Container& other)" << std::endl;
}
template <typename A>
Container(const A& other) {
std::cout << "Container(const A& other)" << std::endl;
}
Container(const std::vector<int>& other) {
std::cout << "Container(const std::vector<int>& other)" << std::endl;
}
~Container() {
std::cout << "~Container()" << std::endl;
}
};
int main(){
Container<int> c1;
Container<int> c2(c1);
Container<int> c3(std::vector<int>());
Container<int> c4();
Container<int> c3(std::string());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Container()
Container(const Container& other)
Container()
~Container()
~Container()
~Container()
Run Code Online (Sandbox Code Playgroud)
问题是:
这里发生了什么事?为什么c3变量似乎被完全忽略了?我有点想法,也许它不能扩展模板,但为什么它不会在编译期间失败?
编译器:gcc版本4.8.1
由于这两个c3
变量都是函数声明(正如Angew在注释中指出的那样),因此最终会声明重载函数.
您声明一个带std::vector<int>()
参数的重载和一个带std::string()
参数的重载.这两个重载不冲突,代码编译.