C++ C++;模板不可理解行为
首先,这段代码很糟糕,我知道,它是用来试验模板的,但我真的不知道它是如何工作的 守则:C++ C++;模板不可理解行为,c++,templates,C++,Templates,首先,这段代码很糟糕,我知道,它是用来试验模板的,但我真的不知道它是如何工作的 守则: #include <iostream> #include <vector> #include <string> template <typename T> class Container { public: Container() { std::cout << "Container()" << std::end
#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;
}
问题是:
编译器:gcc版本4.8.1因为两个
c3
变量实际上都是函数声明(正如Angew在一篇评论中指出的那样),所以您最终会声明重载函数
您声明了一个重载,该重载采用
std::vector()
参数,另一个重载采用std::string()
参数。这两个重载并不冲突,代码可以编译。如前所述:c3、c4和c5是函数声明,但没有人说如何修复它
Container<int> c3((std::vector<int>())); // add parentheses to clarify it's not a function declaration
Container<int> c4; // remove parentheses
Container<int> c3((std::string())); // add parentheses
容器c3((std::vector());//添加括号以澄清它不是函数声明
容器c4;//删除括号
容器c3((std::string());//加括号
c3
,c4
和c5
不是变量,它们是函数,这是因为。对于c4,为true。我错过了,但它只是作为填充物放的。没有c5。对,我没有注意到最后一个也是c3
。不过,它只是第一个代码“C3>代码>函数的另一个重载。@解释为什么它是一个“有效的C++代码”就足够了。@ ZOSKA应该有一个<代码> C5< /代码>:)你正在重新定义<代码> C3<代码>(编译它,因为它被认为是函数重载)为什么它不被当作容器构造器?@ ZoSka最令人烦恼的解析。按照我评论中的链接,我正在考虑用局部变量(不是在“constructor”调用中创建的)来测试它,但不知何故放弃了这个想法。。。或者使用c3{std::vector()}代码>c4{}代码>与C++11。
Container<int> c3((std::vector<int>())); // add parentheses to clarify it's not a function declaration
Container<int> c4; // remove parentheses
Container<int> c3((std::string())); // add parentheses