gpt4 book ai didi

c++ - 如何正确地显式实例化具有完全特化成员的模板类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:14 30 4
gpt4 key购买 nike

假设我们有以下文件:

foo.h

namespace ns
{
template <typename T>
class Foo
{
public:
Foo();

~Foo();

void DoIt();
};
}

foo.cpp

#include "foo.h"

#include <iostream>

namespace ns
{
template <typename T>
Foo<T>::Foo() { std::cout << "Being constructed." << std::endl; }

template <typename T>
Foo<T>::~Foo() { std::cout << "Being destroyed." << std::endl; }

template <>
void Foo<int>::DoIt()
{
std::cout << "Int" << std::endl;
}

template <>
void Foo<double>::DoIt()
{
std::cout << "Double" << std::endl;
}

template class Foo<int>;
template class Foo<double>;
}

假设该类型只会与 int 或 double 作为类型参数一起使用,这是进行显式实例化的正确方法吗?或者您是否也需要在头文件中声明显式特化?

按照我展示的方式使用 visual studio 进行操作,但一位同事在使用 GCC 时遇到了问题(虽然我刚刚检查过,我认为这是由于其他原因,但我还是会发布这个问题)

最佳答案

[temp.expl.spec]/p6(强调我的):

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.

事实上,如果将它们组合在一个 TU 中,clang 和 gcc will issue an error .您需要声明这些明确的特化。


因为我们真的很接近它,所以我也会引用 [temp.expl.spec]/p7,因为我可以:

The placement of explicit specialization declarations for function templates, class templates, variable templates, member functions of class templates, static data members of class templates, member classes of class templates, member enumerations of class templates, member class templates of class templates, member function templates of class templates, static data member templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, static data member templates of non-template classes, member function templates of member classes of class templates, etc., and the placement of partial specialization declarations of class templates, variable templates, member class templates of non-template classes, static data member templates of non-template classes, member class templates of class templates, etc., can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below. When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

关于c++ - 如何正确地显式实例化具有完全特化成员的模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635532/

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