【问题标题】:Understanding C++03 Standard Grammar for Operator Overloading了解运算符重载的 C++03 标准语法
【发布时间】:2017-03-30 10:36:26
【问题描述】:

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

operator-function-id
operator operator
operator operator 模板参数列表?>

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

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

【问题讨论】:

  • 什么是“模板化操作符”?
  • 你可以为你的类重载操作符。这些重载可以是模板函数。
  • @StoryTeller 但明确的特化不能在类范围内。
  • @GillBates 总是有专门的免费函数。
  • @StoryTeller 够公平

标签: c++ language-lawyer c++03


【解决方案1】:

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

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

模板特化 (14.7) 可以通过模板 ID 引用:

模板 ID:

template-name < template-argument-listopt>

模板名称:

identifier

模板参数列表:

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

模板参数:

assignment-expression
type-id
id-expression

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

模板特化 (14.7) 可以通过模板 ID 引用:

简单模板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 ...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!"; 
}

注意operator() 的特化,因为Tdouble。如果你运行这段代码:

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

然后0 将在第一次调用时打印,It's a double! 在第二次调用时打印。

Live demo

【讨论】:

  • 这比直接删除它更有意义,想想看 :)
猜你喜欢
  • 2016-10-28
  • 2021-01-06
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多