C++ 如何绑定和调用模板化类型方法
C++ How to bind and invoke a templated type method
>我正在尝试了解绑定到模板化类型方法的语法。这似乎与我的问题相似,但似乎没有给出绑定和调用模板化类型方法的示例。
这是我的代码示例:
#include <functional>
#include <iostream>
using namespace std;
void DidSomething(int x)
{
cout << "Did something x = " << x << endl;
}
template <typename T>
class Outer
{
public:
void StartSomething()
{
Inner inner;
// below lines cause
// error C2893 Failed to specialize function template
//'unknown-type std::invoke(_Callable &&,_Types &&...)'
auto fnGlobal = std::bind(&::DidSomething);
inner.DoOneThing(fnGlobal);
auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
inner.DoOneThing(fnMethod);
}
void DidSomething(int x)
{
cout << "Did something x = " << x << endl;
}
// example typedef, the actual callback has a lot of args (5 args)
typedef std::function<void(int)> DidSomethingCallback;
private:
class Inner
{
public:
void DoOneThing(DidSomethingCallback fnDidSomething)
{
fnDidSomething(3);
}
};
T t;
};
int main()
{
Outer<bool> outer;
outer.StartSomething();
return 0;
}
>std::bind
要求您为未绑定参数指定占位符,以便返回类型知道预期有多少参数以及将它们传递到何处。因此,您必须编写:
auto fnGlobal = std::bind(&::DidSomething, std::placeholders::_1);
告诉它fnGlobal
接受一个参数,并且应该用该参数调用::DidSomething
。否则,fnGlobal
不会争论。同样
auto fnMethod = std::bind(&Outer<T>::DidSomething, this, std::placeholders::_1);
会让fnMethod
接受一个参数,称之为x
,然后调用this->DidSomething(x)
。如果没有占位符,fnMethod
将不会接受任何参数。
std::bind
的笨重使得在许多情况下避免使用它是可取的。在第一种情况下,写就足够了
// the & is optional
auto fnGlobal = ::DidSomething;
使fnGlobal
成为普通的函数指针。在第二种情况下,可以使用 lambda:
auto fnMethod = [this](int x) { DidSomething(x); };
你用错了std::bind
。您需要传递相应数量的要绑定的参数或占位符,就像创建 std::bind
对象时一样。改变:
auto fnGlobal = std::bind(&::DidSomething);
inner.DoOneThing(fnGlobal);
auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
inner.DoOneThing(fnMethod);
自:
auto fnGlobal = std::bind(&::DidSomething, std::placeholders::_1);
inner.DoOneThing(fnGlobal);
auto fnMethod = std::bind(&Outer<T>::DidSomething, this, std::placeholders::_1);
inner.DoOneThing(fnMethod);
那应该有效
相关文章:
- 在c++中多次调用方法
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 接收字符串并使用它来调用方法C++
- 使用 gmock c++ 在真实对象上调用方法
- 不带预处理器的调用方法/文件的文件名/行号
- JNI从Android调用C++方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 从内部类中的方法从包含类调用方法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么派生类的实例从基类调用方法?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过模板函数对未知类型调用方法
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 创建一个C++DLL以从C#DLL调用方法
- 如何从qt中的类中调用方法
- 如何在不迭代的情况下对数组中的每个元素调用方法
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- C ++:如何在不创建对象的情况下在主函数中调用方法