c++ - 试图从 std::function 获取普通函数指针

标签 c++ c++11 linker function-pointers

我正在尝试从某个 std::function 获取普通函数指针。该任务已在 SO ( like here) 中讨论过多次,并被承认无法解决。但是我尝试了这样的解决方案(为了简单起见,我修复了函数指针签名并退化了普通函数指针的使用):

#include <functional>

typedef int(*fp)(int);

template<int idx, typename F>
struct wrap_f_struct {
    static F impl;

    static int f(int a) { return impl(a); }    
};

template<int idx, typename F>
fp wrap_f(F f) { 
    wrap_f_struct<idx, F>::impl = f;
    return wrap_f_struct<idx, F>::f;
}

int add(int a, int b) { return a + b; }

int main() {
    using namespace std::placeholders; 
    std::function<int(int)> add2 = std::bind(add, _1, 2);

    (wrap_f<1>(add2))(1);
}

好吧,由于某些我无法理解的原因,这不是链接:

/tmp/ccrcFz32.o: In function `int (*wrap_f<1, std::function<int (int)> >(std::function<int (int)>))(int)':
cast_fp_min.cpp:(.text._Z6wrap_fILi1ESt8functionIFiiEEEPS1_T0_[_Z6wrap_fILi1ESt8functionIFiiEEEPS1_T0_]+0x10): undefined reference to `wrap_f_struct<1, std::function<int (int)> >::impl'
/tmp/ccrcFz32.o: In function `wrap_f_struct<1, std::function<int (int)> >::f(int)':
cast_fp_min.cpp:(.text._ZN13wrap_f_structILi1ESt8functionIFiiEEE1fEi[_ZN13wrap_f_structILi1ESt8functionIFiiEEE1fEi]+0x10): undefined reference to `wrap_f_struct<1, std::function<int (int)> >::impl'
collect2: error: ld returned 1 exit status

我的问题是:有人可以向我解释发生此链接错误的确切原因吗?

最佳答案

静态成员变量仅在结构/类中声明。它们也需要定义,而您不需要这样做。

添加例如

template<int idx, typename F>
F wrap_f_struct<idx, F>::impl;

关于c++ - 试图从 std::function 获取普通函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348178/

相关文章:

c++ - 有没有一种方法可以在传递左值时指定不同的函数,而在不传递左值时指定另一个函数?

c - 如何用从偶数地址边界开始的两个字节值填充 S-record?

c++ - 使用 gl3w 的 OpenGL

c++ - 缺少 unique_ptr 和 friend operator= overload

c++ - 想评估两个 sockaddr_in 结构之间的比较

c++ - 使用 Intel 编译器从 C++ 调用 Fortran 子例程

c++ - Vulkan:渲染时内存泄漏

引用 vector 中的 unordered_map 时出现 C++11 段错误

c++ - 从 UTF-8 转换为 UTF-16 的 "codecvt_utf8_utf16"和 "codecvt_utf8"之间的区别

c++ - 如何将 C++ 目标文件与 ld 链接