Jav*_*Man 14 c++ language-lawyer c++03
重载运算符的标准C++ 03语法如下:
operator-function-id:
运算 符运算符
运算 符 < template-argument-list?>
第一个是我们通常使用的普通运算符重载语法,例如
Myclass operator + (Myclass s) {...}
Run Code Online (Sandbox Code Playgroud)
但第二种选择意味着什么呢?特别是,在什么情况下我们使用template-argument-list?在快速浏览一下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("%d\n",s);
return 0;
}
output:118
Run Code Online (Sandbox Code Playgroud)
允许操作符函数模板专门化的语法规则仍然存在于C++ 11中,它只是在不同的地方.
[temp.names]/1(C++ 03):
模板特化(14.7)可以通过template-id引用:
模板id:
Run Code Online (Sandbox Code Playgroud)template-name < template-argument-listopt>模板名称:
Run Code Online (Sandbox Code Playgroud)identifier模板参数列表:
Run Code Online (Sandbox Code Playgroud)template-argument template-argument-list , template-argument模板参数:
Run Code Online (Sandbox Code Playgroud)assignment-expression type-id id-expression
[temp.names]/1(C++ 11):
模板特化(14.7)可以通过template-id引用:
简单模板id:
Run Code Online (Sandbox Code Playgroud)template-name < template-argument-listopt>模板id:
Run Code Online (Sandbox Code Playgroud)simple-template-id operator-function-id < template-argument-listopt> <- HERE literal-operator-id < template-argument-listopt>模板名称:
Run Code Online (Sandbox Code Playgroud)identifer模板参数列表:
Run Code Online (Sandbox Code Playgroud)template-argument ...opt template-argument-list , template-argument ...opt模板参数:
Run Code Online (Sandbox Code Playgroud)constant-expression type-id id-expression
这可能是因为语法规则operator-function-id在上下文中被引用,其中该模板参数列表没有意义,因此他们将规则移动到更合理的地方</ conjecture>.
以下是此规则的实例示例:
struct foo{
template <typename T>
void operator() (T t) { std::cout << t; }
};
template <>
void foo::operator()<double> (double) {
std::cout << "It's a double!";
}
Run Code Online (Sandbox Code Playgroud)
注意专业化operator()的时候T是double.如果您运行此代码:
foo f;
f(0);
f(0.0);
Run Code Online (Sandbox Code Playgroud)
然后0将打印第一个电话,It's a double!第二个电话打印.
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |