鉴于此代码:模板重载麻烦
#include <string>
#include <vector>
#include <iostream>
template <typename T>
std::string stringify(const T&) {
return "{?}";
}
template <typename T>
std::string proxy(const T& in) {
return stringify(in);
}
// trying to specialize "stringify()"
template <typename T>
std::string stringify(const std::vector<T>& in) {
return "vector specialization!";
}
template <>
std::string stringify(const std::vector<int>& in) {
return "INT vector specialization!";
}
int main() {
std::cout << proxy(1); // calls the 1st
std::vector<int> intVec;
std::cout << proxy(intVec); // calls the 1st
std::vector<double> dblVec;
std::cout << proxy(dblVec); // calls the 1st
return 0;
}
我怎样才能proxy<>
后专门为stringify()
vector<>
?
目前我得到{?}{?}{?}
如果我删除这一个 - stringify(const std::vector<T>& in)
那么vector<int>
开始变得调用,因为这将是第一的专业化。
然后我会得到{?}INT vector specialization!{?}
有什么办法调用任何的2矢量专业化字串功能从proxy()
- 如果它们被定义最后 - 在proxy()
功能之后?
有没有办法部分专注于vector<>
并仍然从proxy<>
打电话?
我不想专门为vector<int>
,vector<double>
,vector<UserType>
...
编辑:忘了提我需要这个C++98
非常感谢!你救了我的屁股!我喜欢它,当C++魔术工作,我不明白它 - 仍然试图不学习ADL :)生命是短暂的。 – onqtam
@onqtam ADL是非常重要的 - 毕竟它是如何'标准:: cout <<“你好,世界!”'工作! – Barry
刚刚发现,这不能在VC++ 6下编译...也许ADL是坏的(只有当使用模板重载!免费函数重载罚款) - 它说在'''代理()'''如果有超过1个专业化,该调用是不明确的。也许是时候放弃对它的支持 – onqtam