【问题标题】:How do I define a static array to member functions of a templated class?如何为模板类的成员函数定义静态数组?
【发布时间】:2012-05-16 15:34:17
【问题描述】:

我想做以下事情:-

#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

【问题讨论】:

  • 您是否尝试在A&lt;I&gt;::fptr 之前添加typename
  • 实际上阅读错误信息确实经常帮助...
  • 我尝试添加 typename 并得到了一些不同的(甚至更令人困惑的错误消息)。诀窍是添加 const typename 而不仅仅是 typename。
  • @owagh:读取错误消息是可以迭代多次次的事情。添加typename,得到一个错误,说你在声明别的东西,阅读错误信息,看看它们有什么不同......

标签: c++ arrays templates static function-pointers


【解决方案1】:

两件事。

  1. fptrdependent type,所以你需要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 在 cmets 中指出的那样,您的声明是 const,因此定义也必须是 const

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

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

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

【讨论】:

    【解决方案2】:

    您需要在A&lt;I&gt;::fptr 之前添加const typenametypename 用于告诉编译器 fptrA&lt;I&gt; 中的一个类型。

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

    【讨论】:

      【解决方案3】:

      typename 用作:

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

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

      【讨论】:

        猜你喜欢
        • 2017-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多