专门化成员函数模板实例化后的错误,以及成员函数的顺序 [英] Specialization of member function template after instantiation error, and order of member functions

查看:207
本文介绍了专门化成员函数模板实例化后的错误,以及成员函数的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下位代码无法在gcc 4.5.3上编译

  struct Frobnigator 
{
template< typename T>
void foo();

template< typename T>
void bar();
};

template< typename T>
void Frobnigator :: bar()
{
}

template< typename T>
void Frobnigator :: foo()
{
bar< T>();
}

模板<> // error
void Frobnigator :: foo< bool>()
{
bar< bool>();
}

模板<>
void Frobnigator :: bar< bool>()
{
}

int main()
{
}

错误信息:'void Frobnigator :: bar 'after instantiation 。我最后通过使 Frobnigator :: bar< bool>()的特殊化出现在之前解决这个问题Frobnigator :: foo< bool>() / code>。显然,方法的顺序很重要。



为什么是上面代码的以下lite版本,其中 bar 的特殊化出现在通用版本,有效?

  struct Frobnigator 
{
template< typename T>
void foo();
};

template< typename T>
void Frobnigator :: bar()
{
}

模板<>
void Frobnigator :: bar< bool>()
{
}

int main()
{
}

解决方案

您的第一个代码标准不正确。



n3376 14.7.3 / 6


如果模板,成员模板或类模板的成员是明确专用的,那么专门化应在第一次使用该专门化之前被声明,这将导致在发生这种使用的每个翻译单元中发生隐式实例化;



在您的情况下 - bar 函数的隐式实例化在显式专门化声明之前,在 foo< bool> 中的用法需要类型 bool


The following bit of code fails to compile on gcc 4.5.3

struct Frobnigator
{
    template<typename T>
    void foo();

    template<typename T>
    void bar(); 
};

template<typename T>
void Frobnigator::bar()
{
}

template<typename T>
void Frobnigator::foo()
{
    bar<T>();
}

template<>      // error
void Frobnigator::foo<bool>()
{
    bar<bool>();
}

template<>
void Frobnigator::bar<bool>()
{
}

int main()
{
}

Error message: specialization of ‘void Frobnigator::bar() [with T = bool]’ after instantiation. I finally resolved this problem by having the specialization of Frobnigator::bar<bool>() appear before Frobnigator::foo<bool>(). Clearly the order in which the methods appear matter.

Why then is the following lite version of the above code, in which the the specialization of bar appears after the generic version, valid ?

struct Frobnigator
{
    template<typename T>
    void foo();
};

template<typename T>
void Frobnigator::bar()
{
}

template<>
void Frobnigator::bar<bool>()
{
}

int main()
{
}

解决方案

Your first code is not correct by standard.

n3376 14.7.3/6

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

In your case - implicit instantiation of bar function with type bool is required by it's usage in foo<bool>, before explicit specialization declaration.

这篇关于专门化成员函数模板实例化后的错误,以及成员函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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