模板函数类型C++的后期绑定
Late binding of template function types C++
我有一个类似的模板函数
template < typename T>
void Foo::func(T t)
{
}
和一个调用方函数
void FOO::func2()
{
std::function<void(const Foo&)> mp;
mp = std::bind(&Foo::func);
...
..
..
//Finally
mp();
}
这会导致编译错误,因为我没有指定类型mp = std::bind(&Foo::func);
。问题是我当时不知道是什么类型的,但直到后来我才知道。有什么想法吗?
成员函数必须绑定到this
,并且必须实例化模板:
std::function<void(const FOO&)> mp;
mp = std::bind(&FOO::func<const FOO&>, this, std::placeholders::_1);
mp(*this);
实时演示
现在,如果您不知道bind
点的输入参数的类型,一种选择是使用通用lambdas而不是std::bind
和std::function
:
void FOO::func2() {
auto mp = [this](auto t) { func(t); };
...
mp(/*call here with what ever*/);
}
实时演示
代码中存在一些问题,导致编译失败。
- 当
bind
像这样的成员函数时,需要将引用或指针绑定到有效对象(this
) bind
需要一个占位符,基本上是断言在调用函子时将为该"位置"提供一个参数- 在调用
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
注意:"类型"必须与std::function
中指定的类型匹配(或转换为)。
std::function<void(const Foo&)> mp;
这是接受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));
};
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 在基于范围的for循环中使用结构化绑定声明
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 视觉studo 2019中的漫画和静态/动态绑定
- 将自由函数绑定为类成员函数
- 将常量指针引用绑定到非常量指针
- 在派生类中绑定非静态模板化成员函数
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 在 openGL 中多次绑定缓冲区
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 使用结构化绑定'Reflection'
- 为什么 std::绑定错误参数可以成功?
- 如何绑定 C++ gRPC 客户端的网络接口
- 在 openmp 中,omp_get_thread_num是否绑定到物理线程?
- C++绑定(已弃用)
- 运行时错误:引用绑定到类型为"int"的空指针
- 有没有办法将重载的类函数绑定到函数对象?
- 替换 C++17 中移除的绑定 1st