Converting a reference parameter of a function pointer to const

Code example:

class Foo;
typedef void (*fnptr)(Foo &foo);
fnptr gFn;
void myfoo(const Foo &foo) {}

int main() {
    gFn = &myfoo;
}

The following error failed with clang:

main.cpp:9:9: error: assigning to 'fnptr' (aka 'void (*)(Foo &)') from incompatible type
      'void (*)(const Foo &)': type mismatch at 1st parameter ('Foo &' vs 'const Foo &')
    gFn = &myfoo;
        ^ ~~~~~~
1 error generated.

GCC also fails with a similar error. Passing a pointer instead of a link also

I really don't understand why this is a mistake. A function that takes const Foo & also takes Foo & as an argument, and in both cases a pointer is passed. I would like to understand why this is a mistake.

+4
source share
2 answers

The signature function void(*)(const Foo&) does not match void(*)(Foo&).

, rvalues void myfoo(const Foo&), void myfoo(Foo&). , , , .

.

:

class Foo{};

using FooPtr = void(*)(Foo&);
using ConstFooPtr = void(*)(const Foo&);

void fooNonConst(Foo&) { }
void fooConst(const Foo&) { }


int main() {
    FooPtr ptr1 = &fooNonConst;
    ConstFooPtr ptr2 = &fooConst;

    ptr1(Foo{});   //Not OK
    ptr2(Foo{});   //Ok
}
+2

, . ? , , . , , ? , , . , ++ 98 , . ++ 11 .

, , , , !

, myfoo:

void myfoo_wrap(Foo &foo) {
    myfoo(foo);
}

, , , . , : , ...

+1

Source: https://habr.com/ru/post/1678271/


All Articles