繁体   English   中英

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

[英]How do I define a template member function outside of a full specialized template class's definition?

以下代码可以成功构建。

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

显式专门化的类模板的成员以与普通类的成员相同的方式定义,而不使用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;
}

演示


请注意,如果您没有显式专门化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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM