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

C++ 理解C++;03运算符重载的标准语法,c++,language-lawyer,c++03,C++,Language Lawyer,C++03,重载运算符的标准C++03语法如下所示: 操作员功能id: 操作员操作员 运算符运算符 第一种是我们通常使用的普通运算符重载语法,例如 Myclass operator + (Myclass s) {...} 但第二种选择意味着什么?特别是,在什么情况下我们使用模板参数列表?在快速查看C++11之后,我发现第二种形式已从标准中删除。它的初衷是什么 编辑:在使用VC++2010进行测试后,下面是使用上述语法的一种方法,尽管对我来说没有多大意义: class K { public: int

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

操作员功能id:
操作员操作员
运算符运算符<模板参数列表?>

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

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("%d\n",s);
    return 0;

}

output:118
K类{
公众:
INTA;
模板
整数运算符+(整数b){
返回a+b+b;
}
};
int _tmain(int argc,_TCHAR*argv[]
{
K;
k、 a=1;
int-s;
s=k.算子+(2);
printf(“%d\n”,s);
返回0;
}
产出:118

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

[临时名称]/1(C++03)

模板专用化(14.7)可通过模板id引用:

template-name < template-argument-listopt>
template-name < template-argument-listopt>
simple-template-id
operator-function-id < template-argument-listopt> <- HERE
literal-operator-id < template-argument-listopt>
模板id:

template-name < template-argument-listopt>
template-name < template-argument-listopt>
simple-template-id
operator-function-id < template-argument-listopt> <- HERE
literal-operator-id < template-argument-listopt>
模板参数列表:

template-argument
template-argument-list , template-argument
template-argument ...opt
template-argument-list , template-argument ...opt
模板参数:

assignment-expression
type-id
id-expression
constant-expression
type-id
id-expression
[临时名称]/1(C++11)

模板专用化(14.7)可通过模板id引用:

template-name < template-argument-listopt>
template-name < template-argument-listopt>
simple-template-id
operator-function-id < template-argument-listopt> <- HERE
literal-operator-id < template-argument-listopt>
简单模板id:

template-name < template-argument-listopt>
template-name < template-argument-listopt>
simple-template-id
operator-function-id < template-argument-listopt> <- HERE
literal-operator-id < template-argument-listopt>
模板参数列表:

template-argument
template-argument-list , template-argument
template-argument ...opt
template-argument-list , template-argument ...opt
模板参数:

assignment-expression
type-id
id-expression
constant-expression
type-id
id-expression
这可能是因为语法规则运算符函数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!"; 
}
然后,第一次呼叫将打印
0
,而且
是双精度第二个


什么是“模板运算符”?您可以为类重载运算符。这些重载可以是模板函数。@StoryTeller但显式专门化不能在类范围内。@GillBates总是有专门化作为自由函数。@StoryTeller Fair Enough这比完全删除它更有意义,想想看:)请参见。