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

时间:2014-09-12 02:33:16

标签: 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)
      ^

我在哪里弄错了?

1 个答案:

答案 0 :(得分:4)

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

  

明确专门的类模板的成员在。中定义   与普通类的成员相同,而不是使用   template<>语法。定义一个成员时也是如此   明确专门的成员类。但是,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;
}
相关问题