包装器函数可以重构吗?
Can the wrapper functions be refactored
>我有一个C++函数的集合,这些函数都接受来自同一组类型(下面的示例中的TypeA
,TypeB
和TypeC
(的类型作为模板参数。为了简化这些函数对 python 的公开,我想为每个函数定义一个函数,该函数不将类型作为模板参数,而是作为字符串参数,如下所示:
template<typename dataType>
int function(int arg)
{
...
}
int function(int arg, string type)
{
if (type == "type_A")
{
return function<TypeA>(arg);
}
else if (type == "type_B")
{
return function<TypeB>(arg);
}
else if (type == "type_C")
{
return function<TypeC>(arg);
}
else
{
std::cerr << "Invalid type!" << std::endl;
exit(1);
}
}
目前,我以这种方式包装所有函数,但这会导致大量代码重复,所以我想知道是否有更好的方法来做到这一点,也许使用预处理器指令?
减少if/else
逻辑的一种方法是存储std::function
对象的映射,并使用映射进行正确的调用。
int function(int arg, std::string type)
{
using FMap = std::map<std::string, std::function<int(int)>>;
static const FMap fmap{{"type_A", [](int arg) { return function<TypeA>(arg); }},
{"type_B", [](int arg) { return function<TypeB>(arg); }},
{"type_C", [](int arg) { return function<TypeC>(arg); }}};
auto iter = fmap.find(type);
if ( iter != fmap.end() )
{
return iter->second(arg);
}
std::cerr << "Invalid type!" << std::endl;
exit(1);
return 0;
}
如果愿意重命名函数模板,可以简化构造函数图的代码。
template <typename T>
int fun_2(int arg) { ... }
int function(int arg, std::string type)
{
using FMap = std::map<std::string, std::function<int(int)>>;
static const FMap fmap{{"type_A", fun_2<TypeA>},
{"type_B", fun_2<TypeB>},
{"type_C", fun_2<TypeC>}};
auto iter = fmap.find(type);
if ( iter != fmap.end() )
{
return iter->second(arg);
}
std::cerr << "Invalid type!" << std::endl;
exit(1);
return 0;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 将具有相反操作数的两个函数重构为一个
- 重构类:无法将派生类中成员函数的公共代码移回基类
- 重构MFC消息映射以包括完全限定的成员函数指针
- 包装器函数可以重构吗?
- 重构嵌套绑定以使用 lambda 函数
- 重构模板函数中的常量表达式 if 语句
- 重构现有包装类,以使用与包装器本身相同的构造函数参数包装 T
- 重构许多函数以优雅地接收任何类型的参数(模板<any>)
- 重构,其中唯一函数具有不同的参数
- 函数参数已更改:如何重构代码,尽可能少
- 使用相同的参数重构静态成员函数
- 使用函数对象重构 C++ 代码
- 重构构造函数以使用初始化列表
- 重构多个重复的函数,只在最内层作用域不同
- Qt Creator重构:提取函数