gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:18:26 26 4
gpt4 key购买 nike

我想做以下事情:-

#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

最佳答案

两件事。

  1. fptr 是一个 dependent 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 在评论中指出的那样,您的声明是 const,因此定义也必须是 const

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

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

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

关于c++ - 如何为模板类的成员函数定义静态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com