我有两个基本函数不同的参数类型,但在这些代码中大部分是相同的。因为我不想重复代码,所以我这样做:
bool func(std::string x)
{
if(x=="true")
return true;
return false;
}
bool func(int x)
{
if(x!=-1)
return true;
return false;
}
bool fun( auto x,bool (*f)(auto ))
{
return (*f)(x);
};我已经使用auto关键字来兼容这两个功能,但它有一些错误,所以我需要你的支持。
发布于 2019-05-12 13:07:28
您可以使用模板来实现fun
template<typename T>
bool fun(T x, bool (*f)(T)) {
return f(x);
}但同时,您也可以使fun更通用一些。通过这种方式,它也可以使用带有自定义()操作符的对象(例如std::function、lambdas等):
template<typename T, typename F>
bool fun(T x, F f) {
return f(x);
}发布于 2019-05-12 13:26:01
您不能在函数声明中使用auto,而应尝试使用类似以下内容的模板
bool func(std::string x)
{
if(x=="true")
return true;
return false;
}
bool func(int x)
{
if(x!=-1)
return true;
return false;
}
template<typename T>
bool fun(T x,bool (*f)(T))
{
return (*f)(x);
}
int main(int argc, char* argv[])
{
std::string str = "Test";
fun(str, func);
int x = 2;
fun(x, func);
return 0;
}https://stackoverflow.com/questions/56096294
复制相似问题