经过一些试验和很多错误之后,我发现它对模板运算符不是很有用。作为一个例子:关于C++模板和运算符
class TemplateClass
{
//Generalized template
template<TType>
TType& operator[](const std::string& key)
{
return TType;
}
//Specialized template for int
template<>
int& operator[]<int>(const std::string& key)
{
return 5;
}
//Specialized template for char
template<>
char& operator[]<char>(const std::string& key)
{
return 'a';
}
}
int main()
{
TemplateClass test;
//this will not match the generalized template.
test["test without template will fail"];
//this is not how you call an operator with template.
test<char>["test with template will fail"];
//this works!
test.operator[]<int>["test will work like this"];
return 0;
}
因此,为了使与模板的操作是很丑陋的(除非您是入啰嗦了,真的是谁?)这就是为什么我一直在使用功能“”代替运营商。我的问题是为什么丑陋?为什么需要包含操作员关键字。我的猜测是,它与转换运算符的一些后端魔术不使用括号来进行参数有关,是否有解决方法?提前致谢。
试验和错误,哦,你可以保存的时间,你读过一本书... – JoshD 2010-10-21 17:20:18
请注意,如果运算符采用模板参数类型的参数(如模板 int&operator [](const T&key )然后编译器可以从你传递的参数中推导出模板参数 –
2010-10-21 17:21:56
我的问题是WTF?你为什么要尝试这样做?专业化是应该避免的(如果可以的话)和模板化操作符应该只用于编译器可以通过模板参数推导规则计算出模板参数,对于C++模板相关书籍,我可以推荐“C++模板 - 完整指南” – sellibitze 2010-10-21 17:23:56