如何在类/函数模板中传递 void 参数
嘿,我正在尝试创建一个按钮模板类,它是用按钮在按下时收到的(例如鼠标位置)和指向应该调用的函数的指针构造的。
然而,按钮通常返回 void 并且不带任何参数(您按下的按钮会发生一些事情:它们不带任何参数,它们被按下然后只做一些事情。)所以我将如何生成类成员函数,因为显然我不能将 void 作为参数类型?
这是源代码(如果有帮助的话):
template<typename Return = void, typename Arg1 = void, typename Arg2 = void>
class Button
{
private:
boost::function<Return (Arg1, Arg2)> Function;
//Return (*Function)(Arg1, Arg2); // this didn't work so i tried boost::function
public:
void Activate(Arg1, Arg2){ Function(Arg1, Arg2) ;};
void SetFunction(Return (*Function)(Arg1, Arg2)){
this->Function= Function;};
//constructors
Button(){ Function= 0;};
Button( Return (*Function)(Arg1, Arg2)){
this->Function = &Function; };
};
Hey i'm trying to make a Button template class, which is constructed with the the button would recieve when pressed (such as mouse position), and a pointer to the function that should be called.
However buttons often return void and take no arguments (Buttons that you press and something happens: they don't take any arguments, they're pressed and then just do something.) so how would i generate the classes member functions since apparently i can't have void as an argument type?
Here's the source if it's helpful:
template<typename Return = void, typename Arg1 = void, typename Arg2 = void>
class Button
{
private:
boost::function<Return (Arg1, Arg2)> Function;
//Return (*Function)(Arg1, Arg2); // this didn't work so i tried boost::function
public:
void Activate(Arg1, Arg2){ Function(Arg1, Arg2) ;};
void SetFunction(Return (*Function)(Arg1, Arg2)){
this->Function= Function;};
//constructors
Button(){ Function= 0;};
Button( Return (*Function)(Arg1, Arg2)){
this->Function = &Function; };
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以指定 void 类型的模板规范,例如,您可以使用模板类
button
的以下变体:然后,这允许您初始化并使用 void 作为参数,例如,给定void function
Print()
以下内容现在有效:我希望这有助于澄清问题! :)
注意:
nullptr
是一个 C++0x 关键字,如果您的编译器尚未实现它,请使用#define nullptr 0
You can specify a template specification of type void, for example, you could use the following variations of the templated class,
button
:This then allows you to initialize and use void as arguments, for example, given a void function
Print()
the following would now be valid:I hope this helps to clear things up! :)
Note:
nullptr
is a C++0x keyword, if your compiler hasn't implemented it use#define nullptr 0
如果我关注你想要拥有它,以便用户可以有 0-2 个参数作为参数?
如果您愿意使用 c++0x 那么您可以使用可变参数模板。这将允许您根据需要使用任意数量的参数。
if i follow you want to have it so the user can have 0-2 args for the params?
if you are willing to use c++0x then you can use a variadic template. This will allow you to use as many or as few args as you need.