【发布时间】:2014-10-30 10:22:59
【问题描述】:
我有一个模板,其中一个函数被重载,因此它可以处理std::string 参数和模板实例化的参数类型。这工作正常,除非模板是用std::string 实例化的,因为这会导致两个成员函数具有相同的原型。因此,我选择专门针对这种特殊情况使用该功能。然而,似乎编译器(g++ 4.8.1 带有标志-std=c++0x)从来没有达到特化实际上覆盖主模板的地步,并且它在似乎意识到它应该使用特化之前抱怨模棱两可的重载.有没有办法解决这个问题?
#include <iostream>
template<class T>
struct A {
std::string foo(std::string s) { return "ptemplate: foo_string"; }
std::string foo(T e) { return "ptemplate: foo_T"; }
};
template<> //Error!
std::string A<std::string>::foo(std::string s) { return "stemplate: foo_string"; }
int main() {
A<int> a; //Ok!
std::cout << a.foo(10) << std::endl;
std::cout << a.foo("10") << std::endl;
//A<std::string> b; //Error!
//std::cout << a.foo("10") << std::endl;
return 0;
}
这会导致编译错误,即使我根本不使用std::string 进行实例化(似乎编译器在看到专业化之后就使用std::string 进行实例化,并且在它实际处理专业化之前,抱怨专业化反过来会“消除歧义”的模棱两可的过载)。
编译器输出:
p.cpp: In instantiation of 'struct A<std::basic_string<char> >':
p.cpp:10:27: required from here
p.cpp:6:14: error: 'std::string A<T>::foo(T) [with T = std::basic_string<char>; std::string = std::basic_string<char>]' cannot be overloaded
std::string foo(T e) { return "ptemplate: foo_T"; }
^
p.cpp:5:14: error: with 'std::string A<T>::foo(std::string) [with T = std::basic_string<char>; std::string = std::basic_string<char>]'
std::string foo(std::string s) { return "ptemplate: foo_string"; }
^
我希望它在主模板中跳过foo() 的实现并使用专业化而不考虑主模板foo()。是否可以以某种方式完成,可能使用非类型模板参数,或者我是否必须为 std::string 制作一个完全专业化的类模板,其中包含它所暗示的所有代码重复(我不喜欢在这里使用继承)......其他建议?
【问题讨论】:
标签: c++ templates overloading template-specialization