0

I'm trying to assign function pointers to const class methods, to an array. However, I am experiencing some compiler errors I cannot solve from Googling.

This is what I am trying to do:

#include <iostream>
#include <array>

struct S
{
    std::array<bool (*)(int), 2> arr;

    bool foo(int a) const
    { 
        std::cout << a << std::endl; 
        return true;
    }

    bool foo2(int b) const
    { 
        std::cout << b << std::endl; 
        return true;
    }

    S()
    {
        arr[0] = &S::foo;              // Compiler error
        arr[1] = &S::foo2;             // Compiler error

        const bool res1 = arr[0](6); // calls foo ()
        const bool res2 = arr[1](7); // calls foo2()
    }
};

int main()
{
    S s;
    return 0;
}

But I get:

<source>:22:18: error: assigning to 'value_type' (aka 'bool (*)(int)') from incompatible type 'bool (S::*)(int) const': different qualifiers (unqualified vs 'const')
        arr[0] = &S::foo;

Can anyone advise?

(I need raw pointers and std::array, not std::function)

rare77
  • 297
  • 6
  • 2
    Your functions need to be `static`. – πάντα ῥεῖ Jun 10 '23 at 18:17
  • 2
    A million variations on this question, regular functions (global or static class) are not compatible with non-static class functions. Non static class functions must be called, explicitly or implicitly, on an object, this is not required for regular functions. Therefore pointers both kinds of function are not compatible. – john Jun 10 '23 at 18:24
  • `static` or `std::array arr;`. – Evg Jun 10 '23 at 18:29
  • The code above looks like toy code, so it's hard to know what to suggest. Basically you have three choices, 1) make your functions static, 2) change your pointers to pointers to member functions, 3) use something like `std::function` which can bridge the gap between the two kinds of function. – john Jun 10 '23 at 18:30
  • 1
    @john Looks like a self-contained example to me – rare77 Jun 10 '23 at 18:35
  • I'll change them to static, as that is do-able. – rare77 Jun 10 '23 at 18:35
  • @rare77 I'm not denying it's self contained. But I doubt your real code is as stripped down as the code above (toy code wasn't meant as an insult) so there isn't enough background information to advise what course to take. – john Jun 10 '23 at 18:36
  • @john But you must appreciate not everyone can literally copy and paste their actual code here. Firstly there's IP restrictions, secondly it's usually a lot more. Instead i've extracted the core essence of my problem down to a small example. – rare77 Jun 10 '23 at 18:39
  • @rare77 OK great, I'm not sure what we are disagreeing about. If static works for you go for it. – john Jun 10 '23 at 18:40

0 Answers0