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

Understanding C++03 Standard Grammar for Operator Overloading

重载运算符的标准C++03语法如下:

运算符函数 ID:
运算符 运算符
运算符 运算符 < 模板参数列表?>

第一种就是我们平时使用的普通运算符重载语法,例如

Myclass operator + (Myclass s) {...}

但是第二种选择是什么意思呢?具体来说,我们在什么情况下使用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

允许特化运算符函数模板的语法规则在 C++11 中仍然存在,只是在不同的地方。

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

A template specialization (14.7) can be referred to by a template-id:

template-id:

template-name < template-argument-listopt>

template-name:

identifier

template-argument-list:

template-argument
template-argument-list , template-argument

template-argument:

assignment-expression
type-id
id-expression

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

A template specialization (14.7) can be referred to by a template-id:

simple-template-id:

template-name < template-argument-listopt>

template-id:

simple-template-id
operator-function-id < template-argument-listopt> <- HERE
literal-operator-id < template-argument-listopt>

template-name:

identifer

template-argument-list:

template-argument ...opt
template-argument-list , template-argument ...opt

template-argument:

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!"; 
}

注意当 Tdoubleoperator() 的特化。如果您 运行 此代码:

foo f;
f(0);
f(0.0);

那么第一次调用将打印 0,第二次调用将打印 It's a double!

Live demo