C++对类模板的所有实例化进行记账

C++ book-keeping of all instantiations of a class template

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

在我的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, ...>。但是你可以提供&在此工厂中封装额外的所需类型处理逻辑。