使用C ++ 11 is_same检查函数签名?

emb*_*edc 4 c++ signature type-traits c++11

//test.cpp
#include <type_traits>

double* func() {}

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

int main() {}
Run Code Online (Sandbox Code Playgroud)

编译命令:

g++ -std=c++11 -c test.cpp
Run Code Online (Sandbox Code Playgroud)

输出:

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

上面的代码有什么问题?我该如何解决?

Mar*_*rol 5

func是一个函数,您检查它是否为函数的指针,失败了

见:

//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* (*)())
}
Run Code Online (Sandbox Code Playgroud)

我不是函数指针方面的专家,但我了解:

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

也许你可以看到像

1; // is a int
int i = 1; // i is a Lvalue expression 
Run Code Online (Sandbox Code Playgroud)

该线程可能有用:函数指针与函数参考

还有一个更官方的链接:https : //en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions (感谢super

  • @embedc这是由于隐式转换。有关更多详细信息,请参见[功能指针](https://en.cppreference.com/w/cpp/language/pointer)部分。 (4认同)