类型分组模板的显式实例化
Type grouped Explicit Instantiation of templates
如果我有一个模板类,其中包含重载的模板成员函数(使用 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>;
相关文章:
- 检查某些类型是否是模板类 std::optional 的实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 实例化模板时,我是否必须显式显示参数包中的类型?
- 在实例化之前推断函数模板的返回类型
- 对象实例化与类型C++
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 根据实例化点期望不同的类型
- 类模板实例化中的类型转换
- 实例化具有不完整类型的类模板格式不正确(如果该类型是在之后定义的)
- 实例化多种类型的成员函数模板
- C++ 多态模板类,模板类型对象的实例化
- 从模板实例化/类型推断中查找错误消息的实际来源
- MPL地图实例化类型
- SFINAE将实例化类型限制为std::chrono::duration类型
- 实例化类型模板化类的非类型模板化成员函数
- 使用大括号初始化列表或传统的 ctor 语法实例化类型
- 何时检查C++模板实例化类型
- 使LLDB将地址重新解释为指向模板实例化类型对象的指针
- 标准::shared_ptr 失去常量的实例化类型
- c++模板:我可以/如何使用结构体作为模板的实例化类型