Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const member function and typedef, C++

Tags:

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?

like image 918
igntec Avatar asked Aug 08 '16 10:08

igntec


2 Answers

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.

like image 161
alexeykuzmin0 Avatar answered Sep 19 '22 16:09

alexeykuzmin0


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.

like image 41
T.C. Avatar answered Sep 19 '22 16:09

T.C.