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 f; // not fine, 'const' is ignored, so we have 'int f()'
};
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?
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.
This change is made by CWG 295, essentially to ease generic programming. Consider:
template<class F>
void meow(const F& f) { f(); }
void purr();
meow(purr);
Ignoring the extra const
allows this to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With