C++ 如何为模板化类的成员函数定义静态数组?

C++ 如何为模板化类的成员函数定义静态数组?,c++,arrays,templates,static,function-pointers,C++,Arrays,Templates,Static,Function Pointers,我想做以下工作:- #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&g

我想做以下工作:-

#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
};
#包括
模板
甲级{
公众:
一,委员;;
void f(){}
void g(){}
typedef void(A::*fptr)();
静态常数fptr arr[];
};
模板
A::fptr A::arr[]={
&A::f,
&A::g
};
我该怎么做? 我得到以下错误:-

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
g++memeber\u func\u ptr\u array.cpp
memeber_func_ptr_array.cpp:14:1:错误:在“A::fptr”之前需要“typename”,因为“A”是从属作用域
memeber_func_ptr_数组.cpp:17:2:错误:在“;”之前应为非限定id代币

使用
typename
作为:

  template <typename I>
  typename A<I>::fptr A<I>::arr[] = { &A<I>::f, &A<I>::g };
//^^^^^^^^note this
模板
typename A::fptr A::arr[]={&A::f,&A::g};
//^^^^^^^^注意这一点

这是因为
fptr
是一个依赖类型。

您需要在
a::fptr
之前添加
const typename
typename
告诉编译器
fptr
a
中的类型

你可能想看看C++模板:VANDEVORODE和JoSutTIS的完整指南,以获取更多信息。

< P>两件事。

  • 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
    };
    
    只有在同一位置声明和初始化数组时,才能使用数组大小的自动扣除


  • 您是否尝试在
    A::fptr
    之前添加
    typename
    ?实际上,阅读错误消息确实会经常有所帮助……我尝试添加typename,但得到了一些不同的错误消息(甚至更令人困惑)。诀窍是添加const typename,而不仅仅是typename。@owagh:读取错误消息可以多次迭代完成。添加
    typename
    ,得到一个错误,表明您正在声明其他内容,阅读错误消息,查看它们的不同之处。。。
    static const fptr arr[2]; // include size