Reputation: 2578
I'm trying to get plain function pointer from some std::function. The task has been discussed number of times at SO (like here) and was admitted unsolvable. But I tried such a solution (I fixed the function pointer signture and degenerated the usage of a plain function pointer for the sake of simplicity):
#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);
}
Well, this isn't linking for some reason I can't understand:
/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
My question is: can someone explain me the exact reason why this linkage error occurs?
Upvotes: 1
Views: 269
Reputation: 409176
Static member variables are only declared in a structure/class. They need to be defined as well, which you do not do.
Add e.g.
template<int idx, typename F>
F wrap_f_struct<idx, F>::impl;
Upvotes: 1