【问题标题】:How to compare the signature of two functions?如何比较两个函数的签名?
【发布时间】:2019-11-29 09:45:36
【问题描述】:

有没有办法检查两个函数是否具有相同的签名?例如:

int funA (int a, int b);
int funB (int a, int b);
float funC (int a, int b);
int funD (float a, int b);

在本例中,funAfunB 是唯一应该返回 true 的函数组合。

【问题讨论】:

    标签: c++ function c++17 c++-standard-library function-signature


    【解决方案1】:

    基本上你想检查两个函数的类型是否相同:

    std::is_same_v<decltype(funA), decltype(funB)>

    我不会将此称为“比较签名”,因为如果我没记错的话,返回类型不是签名的一部分(因为它不影响重载决议)。

    【讨论】:

    • 返回类型确实参与函数 pointers 的重载解析,它是函数 templates 签名的一部分。
    【解决方案2】:

    您可以使用decltypestd::is_same 检查函数类型。例如

    std::is_same_v<decltype(funA), decltype(funB)>  // true
    

    LIVE

    【讨论】:

      【解决方案3】:

      其他人提到了使用std::is_samedecltype的解决方案。

      现在要概括比较任意数量的函数签名,您可以执行以下操作

      #include <type_traits> // std::is_same, std::conjunction_v
      
      template<typename Func, typename... Funcs>
      constexpr bool areSameFunctions = std::conjunction_v<std::is_same<Func, Funcs>...>;
      

      并比较尽可能多的功能

      areSameFunctions<decltype(funA), decltype(funB), decltype(funC)>
      

      (See Live Demo)


      或者为了减少打字(即没有decltype),将其作为一个函数

      template<typename Func, typename... Funcs>
      constexpr bool areSameFunctions(Func&&, Funcs&&...)
      {
         return std::conjunction_v<std::is_same<Func, Funcs>...>;
      }
      

      简单地调用

      areSameFunctions(funA, funB, funC) 
      

      (See Live Demo)

      【讨论】:

        【解决方案4】:

        作为另一种未提及的可能性:您可以使用typeinfo== 中的typeid

        #include <typeinfo>
        
        if(typeid(funA) != typeid(funB))
            std::cerr << "Types not the same" << std::endl;
        

        【讨论】:

        • GCC 给了我error: non-constant condition for static assertion
        • @HolyBlackCat 啊,这是 RTTI。不知道这些不是constexpr。我现在有一个稍微好一点的例子。
        猜你喜欢
        • 1970-01-01
        • 2021-11-04
        • 2016-04-26
        • 2023-03-03
        • 2011-03-13
        • 1970-01-01
        • 2016-12-08
        • 2018-06-12
        • 1970-01-01
        相关资源
        最近更新 更多