[英]C++ book-keeping of all instantiations of a class template
在我的API中,我有一个类模板template<class T> struct MyType
。 我的API的用户可以使用几种类型实例化模板MyType
(例如MyType<int>, MyType<UserType>, MyType<OtherUserType>
。在编译时是否可以检测到所有实例?例如, 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, ...>
作为“注册”过程的一部分。 但是您可以在此Factory中提供并封装其他必需的类型处理逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.