2

我想做以下事情:-

#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
};

我该怎么做呢?我收到以下错误:-

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
4

3 回答 3

4

两件事情。

  1. 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
    };
    

    正如 jrok 在评论中指出的那样,您的声明也是const如此,定义也必须如此const

  2. 客户端代码(仅包含标题的文件)需要知道数组有多大,因此您需要声明中数组的实际大小:

    static const fptr arr[2]; // include size
    

    只有在同一个地方声明和初始化数组时,才能使用数组大小​​的自动扣除。

于 2012-05-16T15:38:09.157 回答
2

您需要const typenameA<I>::fptr. 在typename那里告诉编译器这fptrA<I>.

您可能需要查看 Vandevoorde 和 Josuttis 的 C++ 模板:完整指南以获取更多信息。

于 2012-05-16T15:38:02.407 回答
0

用作typename

  template <typename I>
  typename A<I>::fptr A<I>::arr[] = { &A<I>::f, &A<I>::g };
//^^^^^^^^note this

这是因为fptr依赖类型。

于 2012-05-16T15:37:47.113 回答