0

要显式实例化类模板,我可以执行以下操作:

//.h
template<typename T>
class Foo{};


//.cpp
template class Foo<float>;

这很好,因为Foo<float>当在许多地方使用该类时,现在只需实例化一次。是否可以Foo<T>使用预定类型的元组显式实例化?可以说元组是std::tuple<float, int, bool>,我想用它来实例化Foo<float>, Foo<int>Foo<bool>

4

1 回答 1

1

如果您想方便地实例化几个Foo模板类,您可以简单地为此提供一个包装器:

template<typename ...Ts>
class MultiFoo : public Foo<Ts>... {};

然后一次实例化几个模板类:

template class MultiFoo<int, double, bool>;

这将为您实例化Foo<int>,Foo<double>Foo<bool>

这是一个演示

如果您实际上有一个元组,那么您可以为此提供一个明确的专业化:

template<typename ...>
class MultiFoo;

template<typename ...Ts>
class MultiFoo<tuple<Ts...>> : public Foo<Ts>... {};

并用以下方法实例化几个Foos:

template class MultiFoo<tuple<int,double, bool>>;

这是一个演示,我在其中添加了自己的元组,以便输出实际可见。这应该与std::tuple.

请注意,如果您想显式实例化模板以便它们在其他翻译单元中可见,则需要为此使用extern关键字。例如

extern template class Foo<int>;

extern template class MultiFoo<int, double, bool>;
于 2020-04-16T14:58:21.957 回答