与声明分开定义模板类的模板成员 [英] Defining a Template Member of a Template Class separately from the Declaration

查看:26
本文介绍了与声明分开定义模板类的模板成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <cstdlib>

template<class A> struct Foo
{
    template<class B> static bool Bar();
};

template<class B> template<class A>  bool Foo<A>::Bar<B>()
{
    return true;
}

int main()
{
    bool b = Foo<int>::Bar<long>();
    b;
}

这会导致链接器错误:

main.obj : error LNK2019: unresolved external symbol "public: static bool __cdecl Foo<int>::Bar<long>(void)" (??$Bar@J@?$Foo@H@@SA_NXZ) referenced in function main

我需要在类模板的声明之外定义这个成员函数.换句话说,我不能这样做:

I need to define this member function outside of the class template's declaration. In other words, I cannot do this:

#include <cstdlib>
template<class A> struct Foo
{
    template<class B> static bool Bar()
    {
        return true;
    }
};

int main()
{
    bool b = Foo<int>::Bar<long>();
    b;
}

我错过了什么?我如何定义这个成员函数模板?所需的语法是什么?

What am I missing? How can I define this member function template? What's the needed syntax?

注意:我使用的是 MSVC 2008,以防万一.

Note: I am using MSVC 2008, in case that's relevant.

编辑

我尝试的第一件事是颠倒templatetemplate的顺序:

The first thing I tried was to reverse the order of template<class A> and template<class B>:

#include <cstdlib>

template<class A> struct Foo
{
    template<class B> static bool Bar();
};

template<class A> template<class B>  bool Foo<A>::Bar<B>()
{
    return true;
}

int main()
{
    bool b = Foo<int>::Bar<long>();
    b;
}

这导致了编译器错误:

.\main.cpp(11) : error C2768: 'Foo<A>::Bar' : illegal use of explicit template arguments

Bar 函数定义的右大括号.

On the closing brace of the definition for the Bar function.

推荐答案

只要把template的顺序倒过来就好了模板.第二个是内部",与成员声明一起使用.见§14.5.2/1.

Just reverse the order of template<class B> template<class A>. The second one is "inner" and goes with the member declaration. See §14.5.2/1.

此外,正如 John 指出的,从 Bar 中删除参数列表.

Also, as John points out, remove the parameter-list from Bar<B>.

// "outer" template: this parameter gets substituted to create "inner" template
template< class A >

// "inner" template stands alone after "outer" substitution
template< class B >

bool
// This will just be a class name after "outer" substitution.
      foo<A>
// This has usual function template syntax
             :: Bar() {

这篇关于与声明分开定义模板类的模板成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆