c++ 03重载操作符的标准语法如下:
operator-function-id :
操作符操作符
operatoroperator <<em> template-argument-list ?>
Myclass operator + (Myclass s) {...}
但是第二个选项是什么意思呢?特别是,在什么情况下使用模板-参数-列表?在快速浏览了c++ 11之后,我发现第二种形式从标准中删除了。它的初衷是什么?
编辑:在vc++ 2010测试后,下面是使用上述语法的一种方法,尽管它对我来说没有多大意义:class K {
public:
int a;
template <int B>
int operator + (int b) {
return a+b+B;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
K k;
k.a=1;
int s;
s=k.operator+<115>(2);
printf("%dn",s);
return 0;
}
output:118
允许运算符函数模板专门化的语法规则在c++ 11中仍然存在,只是在不同的地方。
[temp.names]/1 (C + + 03) :
模板专门化(14.7)可以通过template-id:
来引用模板id:
template-name < template-argument-listopt>
模板名称:
identifier
template-argument-list:
template-argument template-argument-list , template-argument
模板参数:
assignment-expression type-id id-expression
[temp.names]/1 (C + + 11) :
模板专门化(14.7)可以通过template-id:
来引用simple-template-id:
template-name < template-argument-listopt>
模板id:
simple-template-id operator-function-id < template-argument-listopt> <- HERE literal-operator-id < template-argument-listopt>
模板名称:
identifer
template-argument-list:
template-argument ...opt template-argument-list , template-argument ...opt
模板参数:
constant-expression type-id id-expression
这很可能是因为语法规则operator-function-id是在模板参数列表没有意义的上下文中引用的,所以他们将规则移到了更合理的地方
下面是这个规则的一个例子:
struct foo{
template <typename T>
void operator() (T t) { std::cout << t; }
};
template <>
void foo::operator()<double> (double) {
std::cout << "It's a double!";
}
注意T
为double
时operator()
的专门化。如果运行以下代码:
foo f;
f(0);
f(0.0);
第一次调用将打印0
,第二次调用将打印It's a double!
。
现场演示