在 C++ 中,Boost.Any 将允许您以类型安全的方式执行此操作:
void func(boost::any const &x)
{
// any_cast a reference and it
// will throw if x is not an int.
int i = any_cast<int>(x);
// any_cast a pointer and it will
// return a null pointer if x is not an int.
int const *p = any_cast<int>(&x);
}
// pass in whatever you want.
func(123);
func("123");
在 C 中,您将使用 void 指针:
void func(void const *x)
{
// it's up to you to ensure x points to an int. if
// it's not, it might crash or it might silently appear
// to work. nothing is checked for you!
int i = *(int const*)x;
}
// pass in whatever you want.
int i = 123;
func(&i);
func("123");
您似乎反对它,但无论如何我都会推荐它:如果您使用的是 C++,请接受它。不要害怕模板。 Boost.Any 和 void 指针之类的东西在 C++ 中占有一席之地,但它非常小。
更新:
好吧,我正在制作一个小信号 - 插槽 - 连接库
与我的 gui 工具包一起使用。这样我就可以摆脱丑陋的 WNDPROC。一世
需要这些指针进行连接。
如果您需要多目标信号,Boost.Signals 已经提供了完整且经过测试的信号/插槽实现。您可以使用Boost.Bind(或std::bind,如果您有C++0x 编译器)连接成员函数:
struct button
{
boost::signal<void(button&)> on_click;
}
struct my_window
{
button b;
my_window()
{
b.on_click.connect(std::bind(&my_window::handle_click,
this, std::placeholders::_1));
}
void handle_click(button &b)
{
}
void simulate_click()
{
b.on_click(b);
}
};
如果您只想要一个简单的回调,Boost.Function(或std::function,如果您有 C++0x 编译器)会很好用:
struct button
{
std::function<void(button&)> on_click;
}
struct my_window
{
button b;
my_window()
{
b.on_click = std::bind(&my_window::handle_click,
this, std::placeholders::_1);
}
void handle_click(button &b)
{
}
void simulate_click()
{
b.on_click(b);
}
};