c++ - 包装函数可以重构吗

标签 c++

我有一组 C++ 函数,它们都接受来自同一组类型的类型(TypeATypeBTypeC下面的示例)作为模板参数。为了简化这些函数对 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;
}

关于c++ - 包装函数可以重构吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976114/

相关文章:

c++ - 单个目标的 Makefile 多个依赖行?

c++ - 我在哪里可以找到与 Clang 假设的目录结构相同的 mingw32?

c++ - 如何在 C++ 中创建动态对象列表

c++ - Code::Blocks to XCode:导入带有 GUI 的 C++

c++ - 如何仅当类型 T 派生自类型 X 时才允许模板类实例化?

c++ - Windows Media Foundation 中的视频捕获可以用于屏幕捕获吗?

C++ 指针取消引用乘法

c++ - UuidCreate 和 CoCreateGuid 的区别

c++ - 获取 const 引用的迭代器

c++ - 实验性::文件系统链接器错误