gpt4 book ai didi

c++ - 如何在类/函数模板中传递无效参数

转载 作者:太空狗 更新时间:2023-10-29 20:46:54 24 4
gpt4 key购买 nike

嘿,我正在尝试制作一个 Button 模板类,它是用 构造的,按钮在按下时会收到(例如鼠标位置),以及指向应该调用的函数的指针.

但是按钮通常返回 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; };
};

最佳答案

您可以指定类型为 void 的模板规范,例如,您可以使用模板类的以下变体,button:

template <typename rtnVal, typename Val1, typename Val2>
class Button {
private:
rtnVal(*Function)( Val1 val1, Val2 val2 );

public:
Button() : Function( nullptr ) {}

void SetFunction( rtnVal(*func)(Val1, Val2) ) {
Function = func;
}

rtnVal RunFunction( Val1 val1, Val2 val2 ) { return Function( val1, val2 ); }
};

// Special void type, accepting arguments overload:
template < typename Val1, typename Val2 >
class Button< void, Val1, Val2 > {
private:
void(*Function)(Val1 val1, Val2 val2);

public:
Button() : Function( nullptr ) {}

void SetFunction( void(*func)(Val1, Val2) ) {
Function = func;
}

void RunFunction( Val1 val1, Val2 val2 ) { return Function( val1, val2 ); }

};

// Pure void type:
template<>
class Button<void, void, void> {
private:
void(*Function)( void );

public:
Button() : Function( nullptr ) {}

void SetFunction( void(*func)() ) {
Function = func;
}

void RunFunction() {
return Function();
}
};

然后这允许您初始化并使用 void 作为参数,例如,给定一个 void 函数 Print() 现在以下内容将是有效的:

void Print()
{
std::cout << "Function has been called" << std::endl;
}

int main()
{
Button< void, void, void > btn;

btn.SetFunction( Print );

btn.RunFunction();

std::cout << "Finished";
}

我希望这有助于解决问题! :)

注意:nullptr 是一个 C++0x 关键字,如果您的编译器尚未实现它,请使用 #define nullptr 0

关于c++ - 如何在类/函数模板中传递无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838207/

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