[英]How do I define a static array to member functions of a templated class?
I want to do the following :- 我想做以下事情:
#include <iostream>
template <typename I>
class A {
public:
I member_;
void f() {}
void g() {}
typedef void (A::*fptr) ();
static const fptr arr[];
};
template <typename I>
A<I>::fptr A<I>::arr[] = {
&A<I>::f,
&A<I>::g
};
How do I do this? 我该怎么做呢? I get the following errors :- 我收到以下错误:
g++ memeber_func_ptr_array.cpp
memeber_func_ptr_array.cpp:14:1: error: need ‘typename’ before ‘A<I>::fptr’ because ‘A<I>’ is a dependent scope
memeber_func_ptr_array.cpp:17:2: error: expected unqualified-id before ‘;’ token
Two things. 两件事情。
fptr
is a dependent type so you need typename
: fptr
是一个从属类型,因此您需要typename
:
template <typename I> const typename A<I>::fptr A<I>::arr[2] = { // also note the 2 and the const &A<I>::f, &A<I>::g };
And as jrok noted in the comments, your declaration is const
so the definition must be const
as well. 正如评论中jrok所指出的,您的声明是const
因此定义也必须是const
。
Client code (files that just include the header) needs to know how big the array is so you need the actual size of the array in the declaration: 客户端代码(仅包含标题的文件)需要知道数组的大小,因此您需要在声明中使用数组的实际大小:
static const fptr arr[2]; // include size
You can only use the automatic deduction of the size of the array when the array is declared and initialised in the same place. 仅当在同一位置声明和初始化数组时,才可以使用自动减小数组的大小。
You need to add const typename
before A<I>::fptr
. 您需要在A<I>::fptr
之前添加const typename
。 The typename
is there to tell the compiler that fptr
is a type within A<I>
. 的typename
是否有告诉编译器fptr
是中的一个类型A<I>
You might want to look at C++ Templates: The Complete Guide by Vandevoorde and Josuttis for more information. 您可能需要查看Vandevoorde和Josuttis撰写的C ++模板:完整指南,以获取更多信息。
Use typename
as: 使用typename
作为:
template <typename I>
typename A<I>::fptr A<I>::arr[] = { &A<I>::f, &A<I>::g };
//^^^^^^^^note this
It is because fptr
is a dependent type. 这是因为fptr
是从属类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.