C++ 模板函数类型C+的后期绑定+;
我有一个这样的模板函数C++ 模板函数类型C+的后期绑定+;,c++,maps,bind,C++,Maps,Bind,我有一个这样的模板函数 template < typename T> void Foo::func(T t) { } 模板 void Foo::func(T) { } 和一个调用函数 void FOO::func2() { std::function<void(const Foo&)> mp; mp = std::bind(&Foo::func); ... .. .. //Finally mp()
template < typename T>
void Foo::func(T t)
{
}
模板
void Foo::func(T)
{
}
和一个调用函数
void FOO::func2()
{
std::function<void(const Foo&)> mp;
mp = std::bind(&Foo::func);
...
..
..
//Finally
mp();
}
void FOO::func2()
{
std::函数mp;
mp=std::bind(&Foo::func);
...
..
..
//最后
mp();
}
这会导致编译错误,因为我没有指定类型
mp=std::bind(&Foo::func)代码>。问题是当时我不知道是哪种类型,但只有到后来我才能知道。有什么想法吗?成员函数必须绑定到此
并且您必须实例化模板:
std::function<void(const FOO&)> mp;
mp = std::bind(&FOO::func<const FOO&>, this, std::placeholders::_1);
mp(*this);
成员函数必须绑定到此并且必须实例化模板:
std::function<void(const FOO&)> mp;
mp = std::bind(&FOO::func<const FOO&>, this, std::placeholders::_1);
mp(*this);
代码中有一些问题导致编译失败
像这样绑定成员函数时,需要将引用或指针绑定到有效对象(this
)
bind
需要一个占位符,基本上断言在调用functor时将为该“位置”提供一个参数std::function
时,还需要提供适当的参数mp = std::bind(&Foo::func<const Foo&>, this, std::placeholders::_1);
// ^^^ the placeholder
// ^^^^ an object
// ^^^ template argument
mp(*this);
// ^^^ the argument for the std::function
这是一个函数包装器,用于接受const Foo&
并返回void
的函数。为了支持“未知”类型的场景,通用lambda更适合此用途
auto mp = [this](auto arg) { return this->func(arg); };
为了支持仅移动类型(例如,std::unique_ptr
),可以按如下方式修改lambda
auto mp = [this](auto&& arg) {
return this->func(std::forward<decltype(arg)>(arg));
};
auto-mp=[this](auto&&arg){
返回此->函数(std::forward(arg));
};
代码中有一些问题导致编译失败
像这样绑定成员函数时,需要将引用或指针绑定到有效对象(this
)
bind
需要一个占位符,基本上断言在调用functor时将为该“位置”提供一个参数std::function
时,还需要提供适当的参数mp = std::bind(&Foo::func<const Foo&>, this, std::placeholders::_1);
// ^^^ the placeholder
// ^^^^ an object
// ^^^ template argument
mp(*this);
// ^^^ the argument for the std::function
这是一个函数包装器,用于接受const Foo&
并返回void
的函数。为了支持“未知”类型的场景,通用lambda更适合此用途
auto mp = [this](auto arg) { return this->func(arg); };
为了支持仅移动类型(例如,std::unique_ptr
),可以按如下方式修改lambda
auto mp = [this](auto&& arg) {
return this->func(std::forward<decltype(arg)>(arg));
};
auto-mp=[this](auto&&arg){
返回此->函数(std::forward(arg));
};
成员函数绑定到此
。成员函数绑定到此
。