如果我有一个带有重载模板成员函数(使用 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
:可能,但我正在处理一个巨大的存储库,其中我处理的文件几乎无处不在 - 所以如果我走这条路线进行微小的更改,我的构建时间会很长。