2010-08-02 81 views
5

我想提出这样的结果:的std :: TR1 ::的mem_fn返回类型

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

里面的变量,这是什么变量的类型?

这将是这个样子:

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

此外,什么是std::tr1::bind结果的类型?

谢谢!

回答

4

的返回类型都std::tr1::mem_fnstd::tr1::bind的是不确定的。

可以的std::tr1::bind结果存储在一个std::tr1::function

struct ClassA { 
    void Func() { } 
}; 

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

您还可以将std::tr1::mem_fn结果存储在一个std::tr1::function

std::tr1::function<void(ClassA&)> memfun_wrap(std::tr1::mem_fn(&ClassA::Func)); 
+0

我试图使用'的std :: TR1 ::函数<空隙(的MyType *)>乐趣= 的std :: TR1 ::的mem_fn(&ClassA的::方法);',但它不会编译,有什么不对? – Tarantula 2010-08-02 18:13:18

+0

@Tarantula:由'mem_fn'返回的调用对象需要一个引用,而不是指针。查看更新后的答案。 – 2010-08-02 18:17:12

+0

仍然不起作用,我的原型func被:虚拟无效Func键(*的MyType参数)= 0; – Tarantula 2010-08-02 18:19:57

2

mem_fnbind返回类型是未指定。这意味着,根据参数返回不同类型的对象,标准没有规定如何实现该功能的细节。

如果你想找出类型是与特定库实现特定的情况下,是什么(对于理论兴趣,我希望),你总是可以导致错误,并从错误消息的类型。 E.g:

#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); 
0

的功能,可以通过以下方式来实现(你也因此看到的返回类型):你可以试试这个这里的一段代码http://webcompiler.cloudapp.net/。不幸的是,它使用的可变参数模板https://en.wikipedia.org/wiki/Variadic_template这仅仅是C++ 11标准的一部分。

#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; 
} 
+0

你能提供一些关于你的代码的评论/描述吗? – kvorobiev 2015-09-29 19:40:44

相关问题