繁体   English   中英

是否可以使函数模板从函数引用中采用`decltype`?

[英]Is it possible to make a function template take a `decltype` from a function reference?

我一直很难理解std::function模板。 似乎使用了我不知道的魔术。 它的模板参数是class R class... ARGS 但是它可以作为std::function<void>std::function<void()>传递到模板。 参数示例: std::function<void, int, float>std::function<void(int, float)> 是在c ++ 11中引入了第二种语法吗? 我认为这是无效的。

另外,有没有办法获取函数的decltype并将其传递给函数模板? 这将使功能模板的设置变得非常容易。

这是一个例子:

#include <functional>
using namespace std;

///////////////////////////////////////////////////////////////////////////////
// this works
void x() {}
void y(int p0) {}

int main1()
{
  using namespace std::placeholders;
  function<decltype(y)> functors[] = { bind(x), bind(y, _1) };
  functors[0](1);
  functors[1](1);
  return 0;
}

///////////////////////////////////////////////////////////////////////////////
// this doesn't work
struct X
{
    void x() {}
    void y(int p0) {}
    void z(int i, int p0)
    {
      using namespace std::placeholders;
      static function<decltype(&X::y)> functors[] = { bind(&X::x, _1), bind(&X::y, _1, _2) };
      functors[i](this, p0);
    }
};

int main2()
{
  X xobj;
  xobj.z(0, 1);
  xobj.z(1, 1);
  return 0;
}

int main()
{
    return main1() + main2();
}

std::function接受一个模板参数,该参数必须是一种函数类型。 您不能使用std::function<void, int, float> std::function<void(int, float)>是唯一有效的语法。

std::function在C ++ 11中引入。 在此之前没有std::function 但是在TR1中定义了std::tr1::function ,它使用相同的std::function<void(int, float)>语法。

您要查找的decltype内容可能类似于:

template<typename T>
struct transform_to_free_function;

template <typename Target, typename R, typename... Args>
struct transform_to_free_function<R (Target::*)(Args...)>
{
    using type = R(Target*, Args...);
};

注意:1) type现在是public成员2)它应该是函数类型,而不是为此目的的指针。 从指针类型创建非指针类型并std::remove_pointer ,但否则必须在其上使用std::remove_pointer

然后,示例的其余部分可以正常编译:

#include <functional>
using namespace std;

template<typename T>
struct transform_to_free_function;

template <typename Target, typename R, typename... Args>
struct transform_to_free_function<R (Target::*)(Args...)>
{
    using type = R(Target*, Args...);
};

struct X
{
    void x() {}
    void y(int p0) {}
    void z(int i, int p0);
};

void X::z(int i, int p0)
{
    using namespace std::placeholders;
    static function<transform_to_free_function<decltype(&X::y)>::type>
    functors[] = { bind(&X::x, _1), bind(&X::y, _1, _2) };
    functors[i](this, p0);
}

int main()
{
    X xobj;
    xobj.z(0, 1);
    xobj.z(1, 1);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM