gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:11:05 25 4
gpt4 key购买 nike

以下代码在 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 instantiationto 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com