3
我试图做用一个例子是最好的描述:指针数组成员的(补偿)在C模板参数++
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::**)()'
(让我们忽略的意义[针对问题]事实阵列还应类之外声明实际存在)
这如何实现?
非常量模板参数?那是什么? - 数组与模板参数相同。 – 2013-02-15 11:41:42
@KonradRudolph数组对指针的衰减适用,所以实际的类型是'const ptr *'(以前的'ptr *')。指针本身是prvalue。 – ecatmur 2013-02-15 11:42:50
该死的,这是一个愚蠢的问题(你解决了它 - thx!并且为了记录,我没有对你的答案投下赞成票,我打算在一段时间内接受它(当我被允许时) – 2013-02-15 11:45:05