2

I have 2 basic functions differ about type of parameter but code in these most of the same. Because i do not want to repeat code so i do:

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);
};

I have used auto keyword to be compatible with both functions, but it has something wrong so I need your supports.

4
  • 3
    a side comment: if (x) return true; return false; can always be replaced with return (x); Commented May 12, 2019 at 4:58
  • 2
    That's a slightly bizarre mix of templates and raw function pointers. Commented May 12, 2019 at 5:00
  • 1
    @Jaime assuming the function is declared to return bool Commented May 12, 2019 at 5:15
  • @M.M yes, I am talking about return bool Commented May 12, 2019 at 9:48

2 Answers 2

6

You can use templates to implement fun:

template<typename T>
bool fun(T x, bool (*f)(T)) {
    return f(x);
}

But while you're at it, you can also make fun a bit more generic. This way it also works with objects with a custom () operator (e.g. std::function, lambdas, ...):

template<typename T, typename F>
bool fun(T x, F f) {
    return f(x);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot use auto in function declaration, instead try to use templates something like this

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;
}

2 Comments

Maybe std::cout << (fun(str, func) ? "true" : "false") << '\n'; and the same for x to provide a bit of additional feedback on the operation?
"You cannot use auto in function declaration" actually yes in C++20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.