c++模板:我可以调用基于输入类型名称的函数吗?
C++ templates: can I call a function whose name is based on the input type name?
我有一个代码库,其中有许多返回单例的枚举相关函数。它们的名字是公式化的:
enum Foo {...};
const MySingleton* Foo_Singleton();
enum Bar {...};
const MySingleton* Bar_Singleton();
...
是否有可能编写一个c++模板,将选择正确的getter函数名,而不显式列出所有选项?
template <typename EnumT>
inline const MySingleton* Get() {
return EnumT ## _Singleton();
}
我知道我在这里使用了一个无意义的预处理器指令,但我希望它能传达我的目的。我知道我可以为每个枚举编写重载,但是枚举很多,维护起来很麻烦,所以我宁愿避免这种解决方案。
最简单的方法是更改您的命名策略:
enum Foo {...};
const MySingleton* Get(Foo); // instead of const MySingleton* Foo_Singleton();
enum Bar {...};
const MySingleton* Get(Bar); // instead of const MySingleton* Bar_Singleton();
所涉及的机制称为标签调度。现在您可以通过简单的
获得适当的单例实例:Get(Foo{});
其中一种可能性:
// template specification (to be specialized)
template <typename EnumT>
const MySingleton* Get();
#define JOIN_IMPL(a, b) a ## b
#define JOIN(a, b) JOIN_IMPL(a, b)
// template specialization for particular enum
#define DEFINE_GET_SINGLETON(EnumT)
template<>
inline const MySingleton* Get<EnumT>() {
return JOIN(EnumT, _Singleton)();
}
DEFINE_GET_SINGLETON(Foo)
DEFINE_GET_SINGLETON(Bar)
通过使用宏,您可以节省一些输入(以调试为代价-大多数调试器不能逐步执行宏)。
我怀疑将宏和模板混合在一起的解决方案在这里是可能的。
一个可以工作的基于模板的解决方案,但是需要为每个类型声明一个包装器函数。
首先定义这些函数:
const MySingleton* GetSingleton( Foo* var ) { return Foo_Singleton(); }
const MySingleton* GetSingleton( Bar* var ) { return Bar_Singleton(); }
然后输入:
template <typename EnumT>
inline const MySingleton* Get() {
EnumT e;
return GetSingleton( &e );
}
然后编译器将根据EnumT
选取相应的GetSingleton
。
注意,您可以使用宏来声明函数,但我不确定它是否非常有用:
#define DECLARE_WRAPPER(TYPE) const MySingleton* GetSingleton( TYPE* var ) { return TYPE##_Singleton(); }
DECLARE_WRAPPER( Foo )
DECLARE_WRAPPER( Bar )
相关文章:
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 使用此类型函数有什么优势
- 为什么此函数通过类型函数指针调用后,呼叫明智地行为
- 如何使用无类型函数指针调用C++成员函数
- 模板返回类型函数如何在C++中工作
- 具有通用类型函数的动态库[C ]
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 对于需要其他模板参数的类型函数的部分模板专业化
- c++错误的参数类型-函数指针
- 延迟评估模板类型函数
- 在引用或指针返回类型函数上输入
- 具有指针数据类型的非类型函数模板参数
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- C++模板基类的非类型函数模板的 using 声明
- 字符串到类型函数,模板专用化使调用统一
- 自由类型函数可以接受 Unicode 文件名吗?