5
//test.cpp
#include <type_traits>

double* func() {}

static_assert(std::is_same<double*(*)(), decltype(func)>::value, "");

int main() {}

Compile command:

g++ -std=c++11 -c test.cpp

Output:

test4.cpp:6:1: error: static assertion failed:
static_assert(std::is_same<double*(*)(), decltype(func)>::value, "");
^

What's wrong with the code above? How can I fix it?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
embedc
  • 1,485
  • 1
  • 6
  • 20

1 Answers1

6

func is a function and you check if it's a pointer to function, it's fail

See :

//test.cpp
#include <type_traits>
#include <iostream>

double d {};
double* func() { return &d ; }
auto ptr = func;

static_assert(std::is_same<double*(), decltype(func)>::value, "");
static_assert(std::is_same<double*(*)(), decltype(ptr)>::value, "");
static_assert(std::is_same<double*(*)(), decltype(&func)>::value, "");

double* call_func(double*(f)() )
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    return f();
}

int main() {
    call_func(func); // double* call_func(double* (*)())
}

I am not an expert in function pointer, what I understand :

double* func() { return &d ; } // is a function 
auto ptr = func; // ptr is a pointer to a function

May be you can see it like

1; // is a int
int i = 1; // i is a Lvalue expression 

This thread may be usefull : Function pointer vs Function reference

And a more official link : https://en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions (thank to super)

Martin Morterol
  • 2,560
  • 1
  • 10
  • 15
  • also `decltype(&func)` for the second `static_assert()` – max66 Apr 19 '19 at 07:52
  • 4
    @embedc It's due to implicit convertion. See [Pointer to function](https://en.cppreference.com/w/cpp/language/pointer) section for more details. – super Apr 19 '19 at 08:27