类型分组模板的显式实例化

Type grouped Explicit Instantiation of templates

本文关键字:实例化 类型      更新时间:2023-10-16

如果我有一个模板类,其中包含重载的模板成员函数(使用 SFINAE),例如:

template <typename T>
struct Foo{
    Foo(T elem);
    template <typename U = T>
    auto get() -> std::enable_if_t<std::is_same_v<U, int>, U>;
    template <typename U = T>
    auto get() -> std::enable_if_t<std::is_same_v<U, bool>, U>;
    T elem_;
};

现在在我的 CPP 文件中,我必须定义并显式实例化:

template class Foo<int>;
template int Foo<int>::get<int>();
template class Foo<bool>;
template bool Foo<bool>::get<bool>();
// For all types...T, there will be two statements.

按类型进行分组实例化有哪些不同的可能方法 - 例如:

GroupedFooInit<int>(); // does both Foo<int> and Foo<int>::get<int>
GroupedFooInit<bool>(); // similar
.. and so on.

鉴于我必须使用 C++14,我可以想出 2 种解决方法,但不想/喜欢:
1. Macros:可能,但希望强烈避免。
2. Definition in header, no explicit instantiation needed:可能,但我正在处理一个巨大的存储库,其中我处理的文件几乎包含在任何地方 - 所以如果我走这条路进行即使是很小的更改,我的构建时间也是巨大的。

链接到代码片段

您可以通过添加一层来解决问题:

template <typename T>
struct Foo{
  Foo(T elem);
  T elem_;
  T get(){
     return do_get<T>();
     }
  private:
  template <typename U = T>
  auto do_get() -> std::enable_if_t<std::is_same<U, int>::value, U>;
  template <typename U = T>
  auto do_get() -> std::enable_if_t<std::is_same<U, bool>::value, U>;
   };
//If definitions for the do_get functions are provided before these
//explicit template instantiation definitions, the compiler will certainly
//inline those definitions.
template class Foo<int>;
template class Foo<bool>;