igntec igntec - 3 months ago 11
C++ Question

Const member function and typedef, C++

Suppose we want to declare const member function via

typedef
:

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

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


Since
const
is ignored the program compiles fine. Why
const
is ignored for function? Since we can form const pointer in this way the only thing I can think of is 'C heritage'. Does standard say anything about it?

Answer

C++ 14 standard, [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 ]

Example:

typedef void F();

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

So, this is a correct behavior.

Comments