일부 std :: function에서 일반 함수 포인터를 얻으려고합니다. 이 작업은 SO (like here)에서 여러 번 논의되어 해결되지 않았습니다. 이 내가 할 수없는 어떤 이유로 연결되지std :: function에서 일반 함수 포인터를 얻으려고 시도합니다.
#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);
}
음 :하지만 (내가 함수 포인터를 signture 고정과 단순성을 위해 일반 함수 포인터의 사용을 퇴화) 이러한 솔루션을 시도 이해 :
/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
내 질문은 : 누군가가 나에게이 연결 오류가 발생하는 정확한 이유를 설명 할 수 있습니까?
이 질문은 함수 나 포인터 또는 템플릿과는 아무런 관련이 없습니다. C++에서 피곤한 오래된 "정적 클래스 멤버 정의"문제 일뿐입니다. –
귀하의 "솔루션"은 거대한 재방송이 아닙니다. 'wrap_f'의 결과를 의미있는 방식으로 저장 *하는 것은 기본적으로 불가능합니다. –
@KerrekSB wrap_t를 인스턴스화 할 때 다른 정수 상수를 사용하면 (예 : 1) 반환 값을 afaics에 안전하게 저장할 수 있습니다. –