簡體   English   中英

在 C++ 的命名空間中使用 std::bind 和重載方法

[英]Using std::bind with overloaded methods in namespace in C++

#include <iostream>
#include <map>
#include <functional>


namespace xAOD{
  
    
    namespace EgammaParameters{
        
        enum ShowerShapeType{
             var1 = 0,
             var2 = 1,
             var3 = 3
        };
    };
    
    class Photon{
        public:
        
            // I don't want to use this overload
            //double test(float& value, const EgammaParameters::ShowerShapeType information) const {return 1;}
            // I want to use this overload
            double test(const EgammaParameters::ShowerShapeType information) const {return 1;}

        private:

    };
    
};


struct funcLookup
{
    funcLookup(xAOD::Photon * photon)
    {
        //this works without the first overload
        lookup_callback["test"] = std::bind(&xAOD::Photon::test, photon, xAOD::EgammaParameters::ShowerShapeType::var1);
        // static casting doesn't work:
       //lookup_callback["test"] = std::bind(static_cast<double(&)(const xAOD::EgammaParameters::ShowerShapeType)>(&xAOD::Photon::test), photon,xAOD::EgammaParameters::ShowerShapeType::var1);

    }

    double call(std::string name)
    {
        if (lookup_callback.count(name) > 0){
            return lookup_callback[name]();
        }
        else{
            
            std::cerr << "Invalid Function Call "<< std::endl;
            return -1;
        } 
    }
    std::map<std::string, std::function<double(void)>> lookup_callback;
};
    
int main()
{

    xAOD::Photon * photon;
    funcLookup funcMap(photon);
    std::cout<<funcMap.call("test")<<std::endl;


    return 0;
}

我正在嘗試在 class Photon 的命名空間 EgammaParameters 中綁定一個方法(測試)。 據我了解,我需要特別告訴 C++ 它應該使用哪種重載方法,所以我嘗試使用 static 鑄造,如:

std::bind(static_cast<double(&)(const xAOD::EgammaParameters::ShowerShapeType)>(&xAOD::Photon::test), photon,xAOD::EgammaParameters::ShowerShapeType::var1);

但是,這給了我錯誤error: invalid static_cast from type '' to type 'double (&)(xAOD::EgammaParameters::ShowerShapeType) 我錯過了什么?

使用 lambda 更容易:

lookup_callback["test"] = [=] {
     return photon->test(xAOD::EgammaParameters::ShowerShapeType::var1);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM