代码之家  ›  专栏  ›  技术社区  ›  Tarantula

std::tr1::mem\u fn返回类型

  •  5
  • Tarantula  · 技术社区  · 14 年前

    std::tr1::mem_fn(&ClassA::method);
    

    看起来是这样的:

    MagicalType fun = std::tr1::mem_fn(&ClassA::method);
    

    还有,结果类型是什么 std::tr1::bind ?

    3 回复  |  直到 14 年前
        1
  •  5
  •   James McNellis    14 年前

    两者的返回类型 std::tr1::mem_fn std::tr1::bind 未指定。

    标准::tr1::绑定 在一个 std::tr1::function :

    struct ClassA { 
        void Func() { }
    };
    
    ClassA obj;
    std::tr1::function<void()> bound_memfun(std::tr1::bind(&ClassA::Func, obj));
    

    您还可以存储 在一个 std::tr1::函数 :

    std::tr1::function<void(ClassA&)> memfun_wrap(std::tr1::mem_fn(&ClassA::Func));
    
        2
  •  3
  •   UncleBens    14 年前

    的返回类型 mem_fn bind . 这意味着,根据参数的不同,将返回不同类型的对象,并且标准没有规定必须如何实现此功能的细节。

    如果您想在特定库实现的特定情况下找出类型是什么(出于理论上的兴趣,我希望是这样),您总是可以导致错误,并从错误消息中获取类型。例如:

    #include <functional>
    
    struct X
    {
        double method(float);
    };
    
    int x = std::mem_fn(&X::method);
    
    9 Untitled.cpp cannot convert 'std::_Mem_fn<double (X::*)(float)>' to 'int' in initialization
    

    在C++ 0x中,我假设返回类型将是 auto :)

    auto fun = std::mem_fn(&ClassA::method);
    
        3
  •  0
  •   mathgenius    9 年前

    函数可以通过以下方式实现(因此您也可以看到返回类型):您可以在这里尝试这段代码 http://webcompiler.cloudapp.net/ . 不幸的是,它使用可变模板 https://en.wikipedia.org/wiki/Variadic_template

     #include <iostream>
    #include <string>
    
    template <class R, class T, class... Args > class MemFunFunctor
    {
      private:
      R (T::*mfp)(Args... ); //Pointer to a member function of T which returns something of type R and taking an arbitrary number of arguments of any type 
    
    public:
      explicit MemFunFunctor(R (T::*fp)(Args... ) ):mfp(fp) {}
    
      R operator()(T* t, Args... parameters)
      {
          (t->*mfp)(parameters... );
      }
    
    };
    
    template <class R,class T, class... Args> MemFunFunctor<R,T,Args... > my_mem_fn( R (T::*fp)(Args... ) )
    {
        return MemFunFunctor<R,T,Args... >(fp);   
    }
    
    
    class Foo //Test class
    {
        public:
            void someFunction(int i, double d, const std::string& s )
            {
                std::cout << i << " " << d << " " << s << std::endl;
            }
    };
    
    
    int main() //Testing the above code
    {
    
        Foo foo;
        auto f = my_mem_fn(&Foo::someFunction);
    
        f(&foo, 4, 6.7, "Hello World!" ); //same as foo.someFunction(4, 6.7, "Hello World!");
    
        return 0;
    }