Const 成员函数和 typedef,C++

Const member function and typedef, C++

假设我们想通过typedef声明const成员函数:

typedef int FC() const;
typedef int F();

struct A
{
   FC fc;         // fine, we have 'int fc() const'
   const F f;    // not fine, 'const' is ignored, so we have 'int f()'
};

由于 const 被忽略,所以程序可以正常编译。为什么 const 被函数忽略?由于我们可以通过这种方式形成 const 指针,所以我唯一能想到的就是 'C heritage'。标准对此有任何说明吗?

C++ 14 标准,[dcl.fct] pt。 7:

The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. [ Note: a function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. — end note ]

示例:

typedef void F();

struct S {
    const F f; // OK: equivalent to: void f();
};

所以,这是正确的行为。

此更改由 CWG 295 做出,主要是为了简化泛型编程。考虑:

template<class F>
void meow(const F& f) { f(); }
void purr();

meow(purr);

忽略额外的 const 允许这个工作。