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

标签 c++ templates

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

#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/

相关文章:

c++ - 处理模板创建的更好方法?

python - Tensorflow - Deep MNIST 教程 - 将分类器导出到 C++

c++ - 如果成员是模板类,则在初始化列表中初始化某个类的成员

c++ - 在一个 vector 中保存具有不同模板参数的类实例,但保留它们的属性

c++ - 为什么允许 "a.template foo<0>();"即使 "a.foo<0>();"已经足够了?

c++ - 使用 C++ 模板时出现错误 C2955 和错误 C2244

c++ - C、指针和void函数

c++ - 是否可以将重载的提取运算符与重载的算术运算符级联?

c++ - 在不实现纯虚方法的情况下子类化模板类

使用 str_replace 的 PHP 模板?