理解C++ 03运算符重载的标准语法

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)

Tar*_*ama 5

允许操作符函数模板专门化的语法规则仍然存在于C++ 11中,它只是在不同的地方.

[temp.names]/1(C++ 03):

模板特化(14.7)可以通过template-id引用:

模板id:

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
Run Code Online (Sandbox Code Playgroud)

[temp.names]/1(C++ 11):

模板特化(14.7)可以通过template-id引用:

简单模板id:

template-name < template-argument-listopt>
Run Code Online (Sandbox Code Playgroud)

模板id:

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
Run Code Online (Sandbox Code Playgroud)

这可能是因为语法规则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()的时候Tdouble.如果您运行此代码:

foo f;
f(0);
f(0.0);
Run Code Online (Sandbox Code Playgroud)

然后0将打印第一个电话,It's a double!第二个电话打印.

现场演示