gpt4 book ai didi

c++ - 如何从专门的成员函数访问模板参数?

转载 作者:行者123 更新时间:2023-11-30 01:58:46 25 4
gpt4 key购买 nike

#include <stdio.h>

template<typename T, int N>
class A
{
public:
void func();
};
template<typename T, int N>
void A<int, N>::func()
{
printf("%d\n", N);
}
int main()
{
A<int, 3> a;
a.func();
return 0;
}

当我尝试编译这段代码时,g++ 给出了这些错误:

test.cpp:10:22: error: invalid use of incomplete type ‘class A<int, N>’
test.cpp:4:7: error: declaration of ‘class A<int, N>’

我只在 A::func 根本没有专门化并且函数也专门用于 N 时才设法编译它。

我如何为 T 专门化 A::func 并访问 N(它应该可以是任何值)?

最佳答案

如果这是可能的,语法必须是

template<int N>
void A<int, N>::func()
{
printf("%d\n", N);
}

T 不会在模板参数列表中被提及。

但不幸的是,这是不可能的。单个函数(包括成员函数)不能部分特化。

来自标准(在关于部分类模板特化的部分):

(§14.5.5/2) Each class template partial specialization is a distinct template and definitions shall be provided for the members of a template partial specialization (14.5.5.3).

因此,在您的情况下,完成所需任务的最直接方法是部分特化整个类模板:

template<int N>
class A<int,N>
{
public:
void func();
};

template<int N>
void A<int,N>::func()
{
printf("%d\n",3);
}

Working example of this on Coliru (当然,func 的定义可以内联到类模板定义中。)

但是当类模板有许多其他成员时,这可能不是最佳选择,因为您必须重新定义它们:

(§14.5.5/3) [...] A class template specialization is a distinct template. The members of the class template partial specialization are unrelated to the members of the primary template. Class template partial specialization members that are used in a way that requires a definition shall be defined; the definitions of members of the primary template are never used as definitions for members of a class template partial specialization. [...]

在某些情况下,最好声明一个单独的类模板,仅将这个函数作为成员(可能是静态成员,如果不需要访问其他成员——可能传递访问权限的成员 需要作为显式函数参数),然后从实际类模板中引用它(以避免必须部分特化整个类模板)。

关于c++ - 如何从专门的成员函数访问模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16880885/

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