【问题标题】:Checking function signature using C++11 is_same?使用 C++11 is_same 检查函数签名?
【发布时间】:2019-04-19 07:36:08
【问题描述】:
//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】:

    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 
    

    这个帖子可能有用:Function pointer vs Function reference

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

    【讨论】:

    • 还有decltype(&amp;func) 第二个static_assert()
    • @embedc 这是由于隐式转换。有关详细信息,请参阅Pointer to function 部分。
    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多