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)
上面的代码有什么问题?我该如何解决?
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)