c++ - 实例化错误后成员函数模板的特化,以及成员函数的顺序

标签 c++ templates template-specialization

以下代码在 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()
{
}

错误信息:specialization of ‘void Frobnigator::bar() [with T = bool]’ after instantiation .我终于通过 Frobnigator::bar<bool>() 的特化解决了这个问题。出现在 Frobnigator::foo<bool>() 之前.显然,方法出现的顺序很重要。

那为什么是上面代码的以下精简版,其中bar的特化出现在通用版本之后,有效吗?

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

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

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

int main()
{
}

最佳答案

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

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.

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

关于c++ - 实例化错误后成员函数模板的特化,以及成员函数的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112148/

相关文章:

c++ - 使用特殊类中的类模板的内部类型

c++ - OpenGL 缓冲区到属性

c++ - 为什么我在 C++ 线程函数调用中得到重复值?

python - 如何在 Cheetah 模板中使用继承?

c++ - 如何将模板作为模板参数传递给模板?

c++ - 如何通过索引访问枚举类?

c++ - 使用模板特化拆分可变参数包

c++ - 系统托盘中的菜单没有每个 QActions

c++保存对象的分配和删除

c++ - 物理引擎的循环模板类型名依赖