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

问题描述 投票:4回答:1
//test.cpp
#include <type_traits>

double* func() {}

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

int main() {}

编译命令:

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

输出:

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

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

c++ c++11 signature typetraits
1个回答
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* (*)())
}

我不是函数指针的专家,我理解的是:

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

也许你可以看到它

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

这个主题可能很有用:qazxsw poi

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

© www.soinside.com 2019 - 2024. All rights reserved.