gpt4 book ai didi

c++ - 成员函数的模板特化

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

我最近发现了 C++ 中的模板特化

template <typename T>
void fct(void) {}

template <>
void fct<int>(void) {}

int main(void) {
fct<int>();
return 0;
}

我想对类中的成员函数使用模板特化。

class   MyClass {
public:
template <typename T>
static void fct(void) {}

template <>
static void fct<int>(void) {}
};

int main(void) {
MyClass::fct<int>();

return 0;
}

不幸的是,使用 g++ 编译会出现以下错误:

error: explicit specialization in non-namespace scope ‘struct MyClass’
error: template-id ‘toto<int>’ in declaration of primary template

我注意到在主作用域或命名空间中进行模板特化工作,但在结构或类中不起作用。

我在 stackoverflow 上找到了一些关于使用 namespace 的信息,如下面的代码:

namespace myNameSpace {
template <typename T>
void fct(void) {}

template <>
void fct<int>(void) {}
}

class MyClass {
public:
template <typename T>
static void fct(void) {
myNameSpace::fct<T>();
}
};

int main(void) {
MyClass::fct<int>();

return 0;
}

我做错了什么?是否可以使用成员函数进行模板特化?如果没有,解决这个问题的最佳方法是什么?有没有比使用命名空间更好的方法来解决这个问题?

最佳答案

在类定义之后写特化:

class MyClass
{
public:
template <typename T>
static void fct(void) {}
};

template <>
void MyClass::fct<int>() {}

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

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