Check if a class has a member function of a given signature

后端 未结 17 1465
無奈伤痛
無奈伤痛 2020-11-22 03:00

I\'m asking for a template trick to detect if a class has a specific member function of a given signature.

The problem is similar to the one cited here http://www.go

17条回答
  •  感情败类
    2020-11-22 03:10

    I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size_t used_memory() const).

    template
    struct HasUsedMemoryMethod
    {
        template struct SFINAE {};
        template static char Test(SFINAE*);
        template static int Test(...);
        static const bool Has = sizeof(Test(0)) == sizeof(char);
    };
    
    template
    void ReportMemUsage(const TMap& m, std::true_type)
    {
            // We may call used_memory() on m here.
    }
    template
    void ReportMemUsage(const TMap&, std::false_type)
    {
    }
    template
    void ReportMemUsage(const TMap& m)
    {
        ReportMemUsage(m, 
            std::integral_constant::Has>());
    }
    

提交回复
热议问题