gpt4 book ai didi

c++ - boost 功能模板错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:35:58 25 4
gpt4 key购买 nike

我正在开发一个类来管理一些回调,例如鼠标点击或显示(当需要刷新窗口时调用的回调)

回调和句柄保存在 map 中。我正在尝试创建一个可以在 map 中注册回调的函数 (addCallback)。

class CallBackManager {

public:
enum CallBackType {
DISPLAY = 1 << 0,
MOUSE = 1 << 1
};

template<typename T>
void AddCallback(CallBackType type, int hwnd, T f) {

if (type & DISPLAY) {
addDisplayCallback(hwnd, f); // 50 lines of error here
}

if (type & MOUSE) {
addMouseCallback(hwnd, f); // The same here
}

}

private:

void addDisplayCallback(int hwnd, boost::function<void ()> f) {
_display_callback[hwnd] = f;
};

void addMouseCallback(int hwnd, boost::function<void (int, int)> f) {
_mouse_callback[hwnd] = f;
};

std::map<int, boost::function<void ()>> _display_callback;
std::map<int, boost::function<void (int, int)>> _mouse_callback;

};

我这样称呼这些函数:

CallBackManager cbm;

cbm.AddCallBack(
CallBackManager::CallBackType::DISPLAY,
my_handle,
boost::bind(&Foo::Display, this)); // boost::function<void ()>

cbm.AddCallback(
CallBackManager::CallBackType::DISPLAY,
my_handle,
boost::bind(&Foo::Mouse, this, _1, _2)): //boost::function<void (int, int)>

最后的错误是:

error C2784: 'T &boost::_bi::list0::operator [](const boost::reference_wrapper<T> &) const' : could not deduce template argument C:\local\boost_1_57_0_b1\boost\bind\bind.hpp   392

我不明白这个错误

(这里是编译错误的代码) https://ideone.com/BdW1Ln

最佳答案

您正在将 T 类型的函数添加到两个映射中,在相同的静态代码路径中。当然,你过滤它,但那是运行时。这行不通。


只需使用单独的函数。

它更短,更易读。

Live On Coliru

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <map>

class CallBackManager {

public:
enum CallBackType { DISPLAY = 1 << 0, MOUSE = 1 << 1 };
struct display_callback_t;

template <typename F>
void AddDisplayCallback(int hwnd, F f) {
addDisplayCallback(hwnd, f);
}

template <typename F>
void AddMouseCallback(int hwnd, F f) {
addMouseCallback(hwnd, f);
}

void test() {
for (auto& f : _display_callback)
f.second();
for (auto& f : _mouse_callback)
f.second(rand(), rand());
}
private:
void addDisplayCallback(int hwnd, boost::function<void()> f) { _display_callback[hwnd] = f; };

void addMouseCallback(int hwnd, boost::function<void(int, int)> f) { _mouse_callback[hwnd] = f; };

std::map<int, boost::function<void()>> _display_callback;
std::map<int, boost::function<void(int, int)>> _mouse_callback;
};

#include <iostream>
struct Foo {

int my_handle;
CallBackManager cbm;

Foo()
{
cbm.AddDisplayCallback(my_handle, boost::bind(&Foo::Display, this));
cbm.AddMouseCallback(my_handle, boost::bind(&Foo::Mouse, this, _1, _2));
}

void Mouse(int, int) {
std::cout << __PRETTY_FUNCTION__ << "\n";
}
void Display() {
std::cout << __PRETTY_FUNCTION__ << "\n";
}
};

int main() {
Foo instance;
instance.cbm.test();
}

打印

void Foo::Display()
void Foo::Mouse(int, int)

关于c++ - boost 功能模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29602229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com