C++对类模板的所有实例化进行记账
C++ book-keeping of all instantiations of a class template
在我的API中,我有一个类模板template<class T> struct MyType
。我的API用户可以用几种类型(例如MyType<int>, MyType<UserType>, MyType<OtherUserType>
(实例化模板MyType
。在编译时是否可以检测到所有的实例化?要有类似的东西:using AllInstantiations = type_list<int, UserType, OtherUserType>
?我问的原因是,我想注册这些类型。当读取字符串时,可以是"int"、"UserType"或"OtherUserType",我想查找注册的类型并找到匹配的类型。
请考虑任何将包含class ...RegisteredTypes
作为std::tuple<RegisteredTypes...>
参数的"Factory"实现。参见示例:
template <class ... RegisteredTypes>
class Factory
{
public:
using MyRegisteredClassList = std::tuple<MyClass<RegisteredTypes>...>;
using RegisteredTypesList = std::tuple<RegisteredTypes...>;
//Specific type creation Factory method - if encapsulation required
template<class T, class ...T_Args>
static inline MyClass<T> createMyClassInstance(T_Args &&...args)
{
//TODO add 'static_assert'
//for check T as 'RegisteredTypesList' and invoke pretty warning here
return MyClass<T>(std::forward<T_Args>(args)...);
}
//TODO add your method for searching 'string' in 'RegisteredTypesList'
// use c++17 std::apply(), for example
};
此方法的缺点是,作为"注册"过程的一部分,您需要在客户端代码中实例化全局/静态类型Factory<int,OneType,SecondType, ...>
。但是你可以提供&在此工厂中封装额外的所需类型处理逻辑。
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 受约束的成员函数和显式模板实例化
- 对显式实例化的模板函数的未定义引用
- [temp.variadic]中关于包扩展实例化的措辞