首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::tr1::mem_fn返回类型

std::tr1::mem_fn返回类型
EN

Stack Overflow用户
提问于 2010-08-03 01:52:16
回答 3查看 2.8K关注 0票数 6

我想把结果放在这里:

代码语言:javascript
复制
std::tr1::mem_fn(&ClassA::method);

在一个变量中,这个变量的类型是什么?

它看起来像这样:

代码语言:javascript
复制
MagicalType fun = std::tr1::mem_fn(&ClassA::method);

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

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-08-03 02:00:51

std::tr1::mem_fnstd::tr1::bind的返回类型都未指定。

您可以将std::tr1::bind的结果存储在std::tr1::function

代码语言:javascript
复制
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

代码语言:javascript
复制
std::tr1::function<void(ClassA&)> memfun_wrap(std::tr1::mem_fn(&ClassA::Func));
票数 5
EN

Stack Overflow用户

发布于 2010-08-03 02:04:39

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

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

代码语言:javascript
复制
#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 :)

代码语言:javascript
复制
auto fun = std::mem_fn(&ClassA::method);
票数 3
EN

Stack Overflow用户

发布于 2015-09-29 21:15:47

该函数可以通过以下方式实现(因此,您还可以看到返回类型):您可以在http://webcompiler.cloudapp.net/中尝试这段代码。不幸的是,它使用了可变模板https://en.wikipedia.org/wiki/Variadic_template,这些模板只是C++11标准的一部分。

代码语言:javascript
复制
 #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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3390385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档