gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:08:53 26 4
gpt4 key购买 nike

#include <iostream>
#include <vector>
using namespace std;

class test
{

public:

template <typename T>
void f(const std::string& path, std::vector<T>& type_vec)
{
cout << "Base template ";
}

template <>
void f<std::string>(const std::string& path, std::vector<std::string>& type_vec)
{
cout << "Specialization vec ";
}
};

int main()
{
std::vector<int> vec_int;
std::vector<std::string> vec_str;
std::string path = "";
test T;

T.f(path, vec_int);
T.f(path, vec_str);

return 0;
}

出现以下编译错误:

main.cpp:24:15: error: explicit specialization in non-namespace scope 'class test'
template <>
^
main.cpp:25:84: error: template-id 'f' in declaration of primary template
void f<std::string>(const std::string& path, std::vector<std::string>& type_vec)
^

错误 1:是否有解决方法?非命名空间范围(在本例中为类)是否完全不允许专门化?

错误 2:我知道函数模板的部分特化是不允许的。但是,我不明白这是部分特化吗?任何解决方法?

注意:如果函数不是类成员方法,则代码可以正常编译。

最佳答案

在 C++11 中 [temp.expl.spec]/2 要求模板函数的显式特化发生在命名空间范围内。

An explicit specialization shall be declared in a namespace enclosing the specialized template. [...]

因为你必须使用

class test
{

public:

template <typename T>
void f(const std::string& path, std::vector<T>& type_vec)
{
cout << "Base template ";
}
};

template <>
void test::f<std::string>(const std::string& path, std::vector<std::string>& type_vec)
{
cout << "Specialization vec ";
}

也就是说 DR CWG 727已被应用,clang (8.0.0+) 和 MSVS(2015 update 3+) 将编译代码作为 [temp.expl.spec]/2 的新措辞是

An explicit specialization may be declared in any scope in which the corresponding primary template may be defined ([namespace.memdef], [class.mem], [temp.mem]).

这被 C++17 采用,但也被追溯应用于 C++14


已经为 gcc 提交了一份错误报告,但目前还没有任何进展:Bug 85282 - CWG 727 (full specialization in non-namespace scope)

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

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