Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type definition unclear

Tags:

c++

types

In the following C++ code what does double (*) double mean? What kind of a return type is it?

auto get_fun(int arg) -> double (*)(double) // same as: double (*get_fun(int))(double)
{
    switch (arg)
    {
        case 1: return std::fabs;
        case 2: return std::sin;
        default: return std::cos;
    }
}
like image 551
Mudit Sharma Avatar asked Oct 28 '16 10:10

Mudit Sharma


2 Answers

double (*)(double) it's a function pointer signature for a function that takes one double argument and returns double. Generally

X (*)(A, B, C)  // any number of args

is a pointer to function that takes args of types(A, B, C) and returns value of type X, e.g.

X my_func(A, B, C) {
    return X();  // assuming this makes sense
}

would be of the signature above.

So in your case get_fun is a function that returns a function pointer.

like image 141
freakish Avatar answered Oct 07 '22 11:10

freakish


double (*)(double) is type representing a pointer on function taking double and returning double.

like image 44
Jarod42 Avatar answered Oct 07 '22 10:10

Jarod42