【发布时间】:2010-10-21 17:15:53
【问题描述】:
经过一些尝试和很多错误,我发现它对模板运算符不是很有用。举个例子:
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;
}
因此,使用模板制作运算符非常难看(除非您很冗长,而且真的是谁?)这就是为什么我一直使用函数“get”来代替运算符的原因。我的问题是为什么丑?为什么需要包含操作符关键字。我的猜测是,它与转换运算符以不使用括号来接受参数的一些后端魔法有关,有没有办法解决这个问题?提前致谢。
【问题讨论】:
-
反复试验,哦,如果你读一本书,你可以节省的时间......
-
请注意,如果运算符采用模板参数类型的参数(如 template
int & operator[](const T & key) 则编译器可以从参数中推断出模板参数当你调用它时你通过了。 -
我的问题是WTF?你为什么还要尝试这个?应避免专门化(如果可以),并且仅当编译器可以通过模板参数推导规则找出模板参数时,才应使用模板化运算符。至于一本C++模板相关的书,我可以推荐《C++ Templates -- The Complete Guide》。
-
@sellibitze:它必须是模板专业化,愚蠢,因为你不能重载返回类型。 ;-)