gpt4 book ai didi

c++ - 类模板特化中的成员函数语法

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:18 24 4
gpt4 key购买 nike

我有一个类模板,我们称它为A,它有一个成员函数abc():

template <typename T>
class A{
public:
T value;
void abc();
};

我可以在类声明之外实现成员函数 abc(),使用以下语法:

template <typename T>
void A<T>::abc()
{
value++;
}

我想做的是为这个类创建一个模板特化,比如说 int

template <>
class A<int>{
public:
int value;
void abc();
};

问题是为特殊类实现abc()的正确语法是什么?

我尝试使用以下语法:

template <>
void A<int>::abc()
{
value += 2;
}

但是这不能编译。

最佳答案

void A<int>::abc()
{
value += 2;
}

A<int>explicit specialisationA<T> .

http://liveworkspace.org/code/982c66b2cbfdb56305180914266831d1

n3337 14.7.3/5

Members of an explicitly specialized class template aredefined in the same manner as members of normal classes, and not using the template<> syntax.

[ Example:

template<class T> struct A {
struct B { };
template<class U> struct C { };
};
template<> struct A<int> {
void f(int);
};
void h() {
A<int> a;
a.f(16);
}
// A<int>::f must be defined somewhere
// template<> not used for a member of an
// explicitly specialized class template
void A<int>::f(int) { /∗ ... ∗/ }

关于c++ - 类模板特化中的成员函数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12260172/

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