gpt4 book ai didi

c++ - 模板类的模板化构造函数的显式实例化

转载 作者:可可西里 更新时间:2023-11-01 15:24:27 26 4
gpt4 key购买 nike

不确定是Clang 3.2的bug还是违反了C++03,但是貌似模板类的模板化构造函数的显式实例化失败了,但是模板类的模板化成员函数的显式实例化成功了。

例如,下面的代码在 clang++ 和 g++ 下编译都没有问题:

template<typename T>
class Foo
{
public:
template<typename S>
void Bar( const Foo<S>& foo )
{ }
};
template class Foo<int>;
template class Foo<float>;

template void Foo<int>::Bar( const Foo<int>& foo );
template void Foo<int>::Bar( const Foo<float>& foo );
template void Foo<float>::Bar( const Foo<int>& foo );
template void Foo<float>::Bar( const Foo<float>& foo );

而以下代码使用 g++ 编译时没有警告,但使用 clang++ 时失败:

template<typename T>
class Foo
{
public:
template<typename S>
Foo( const Foo<S>& foo )
{ }
};
template class Foo<int>;
template class Foo<float>;

template Foo<int>::Foo( const Foo<int>& foo );
template Foo<int>::Foo( const Foo<float>& foo );
template Foo<float>::Foo( const Foo<int>& foo );
template Foo<float>::Foo( const Foo<float>& foo );

特别是,我看到了以下形式的两条错误消息:

TemplateMember.cpp:12:20: error: explicit instantiation refers to member
function 'Foo<int>::Foo' that is not an instantiation
template Foo<int>::Foo( const Foo<int>& foo );
^
TemplateMember.cpp:9:16: note: explicit instantiation refers here
template class Foo<int>;
^

这是否违反了标准或 clang++ 中的错误?

最佳答案

您似乎发现了一个 GCC 错误。这些都命名了隐式声明的复制构造函数:

template Foo<int>::Foo( const Foo<int>& foo );
template Foo<float>::Foo( const Foo<float>& foo );

根据 [temp.explicit]p4,

If the declaration of the explicit instantiation names an implicitly-declared special member function (Clause 12), the program is ill-formed.

因此 Clang 拒绝此代码是正确的。

关于c++ - 模板类的模板化构造函数的显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15045879/

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