Array of pointer to element (offset) as template parameter in C ++

What I am trying to do is best described by an example:

class A
{
    int f1();
    int f2();
    int f3();

    typedef int (A::*ptr)();

    constexpr static const ptr array[3] =
    {
            &A::f1,
            &A::f2,
            &A::f3,
    };

    template<ptr a[]>
    int sum()
    {
        int s = 0;
        for (int i = 0; i < 3; i++)
            s += (this->*a[i])();
    };

    int f4() { return sum<array>(); };
};

      

Obviously this doesn't work, giving the following output in GCC (in the template instance line, the definition seems fine):

main.cpp: In member function 'int A::sum()':
main.cpp:49:2: warning: no return statement in function returning non-void [-Wreturn-type]
main.cpp: In member function 'int A::f4()':
main.cpp:51:31: error: no matching function for call to 'A::sum()'
main.cpp:51:31: note: candidate is:
main.cpp:44:6: note: template<int (A::** a)()> int A::sum()
main.cpp:44:6: note:   template argument deduction/substitution failed:
main.cpp:51:31: error: could not convert template argument 'A::array' to 'int (A::**)()'

      

(let's ignore the pointless [for the problem] fact that the array must also be declared outside of the class to actually exist)

How can this be achieved?

+3


source to share


1 answer


You forgot to provide const-correctness. Change to:



template<const ptr a[]>
         ~~~~~

      

+6


source







All Articles