gpt4 book ai didi

c++ - 如何在完整的专用模板类定义之外定义模板成员函数?

转载 作者:行者123 更新时间:2023-11-30 01:51:43 24 4
gpt4 key购买 nike

下面的代码可以编译成功。

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

template <class T>
struct Foo
{
template <class S>
void print(const T& t, const S& s);
};

template <>
struct Foo<int>
{
template <class S>
void print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}
};

int main(void)
{
string str("hello");
Foo<int> foo;
foo.print(7, str);
return 0;
}

但是如果我移动成员函数的定义 Foo<int>::print(...)在类的定义之外 Foo<int>像下面一样

template <>
template <class S>
void Foo<int>::print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}

我遇到这样的 GCC 编译错误:

error: too many template-parameter-lists
void Foo<int>::print(const int& t, const S& s)
^

我哪里做错了?

最佳答案

§14.7.3 [temp.expl.spec]/p5:

Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using the template<> syntax. The same is true when defining a member of an explicitly specialized member class. However, template<> is used in defining a member of an explicitly specialized member class template that is specialized as a class template.

print不是类模板。因此,删除 template <> :

template <>
struct Foo<int>
{
template <class S>
void print(const int& t, const S& s);
};

template <class S>
void Foo<int>::print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}

Demo .


请注意,如果您没有明确特化 Foo<int> , 但试图定义 Foo<int>::print直接地,那么你就是显式特化 Foo 的特定隐式实例化的成员。 , 而不是定义显式特化的成员。为此,您需要 template <> :

template <class T>
struct Foo
{
template <class S>
void print(const T& t, const S& s);
};

template <>
template <class S>
void Foo<int>::print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}

关于c++ - 如何在完整的专用模板类定义之外定义模板成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799846/

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