3

我想要做的最好用一个例子来描述:

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>(); };
};

它显然不起作用,在 GCC 中给出以下输出(在模板实例化的行,定义似乎很好):

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::**)()'

(让我们忽略无意义的[问题]事实,即数组也应该在类之外声明为实际存在)

如何做到这一点?

4

1 回答 1

6

您忘记了确保 const 正确性。改成:

template<const ptr a[]>
         ~~~~~
于 2013-02-15T11:39:05.087 回答