Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking function signature using C++11 is_same?

//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?

like image 754
embedc Avatar asked Apr 19 '19 07:04

embedc


1 Answers

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)

like image 183
Martin Morterol Avatar answered Oct 20 '22 03:10

Martin Morterol