3

정적 클래스 함수 Foo::bar()에 대한 함수 포인터가 있고 클래스 형식 (Foo)을 가져 오려고합니다. 지금, 나는 barFoo의 멤버 함수 인 경우에 나는 다음과 같은 유형의 특성처럼 뭔가 대신 정적 기능의 클래스 유형을 얻을 수 있다는 것을 알고정적 클래스 함수의 클래스 형식 가져 오기

template<class T> struct class_of; template<class T, class R> struct class_of<R T::*> { using type = T; };

그러나이 작동하지 않습니다 정적 함수의 경우. 내가 뭘하려는 것은 다음 class_of<Foo::bar>::type == Foo

컴파일러가 모든 관련 정보를 알고 나에게 보인다, 그래서 이것은 어떻게 할 수 있는가?

답변

1

정적 멤버 함수에 대한 베어 함수 포인터는 비 멤버 함수에 대한 함수 포인터 인과 동일한 유형의 입니다.

#include <iostream> 

struct Foo { 
    template<class Arg> 
    static void bar(Arg arg) { 
    std::cout << "called with " << arg << std::endl; 
    } 
}; 

template<class T, class Ret, class... Args> 
struct Wrapper { 
    using F = Ret(*)(Args...); 

    F f_; 

    constexpr Wrapper(F f) noexcept : f_{f} {} 

    template<class... RealArgs> 
    constexpr Ret operator()(RealArgs&&... args) const { 
    return f_(std::forward<RealArgs>(args)...); 
    } 
}; 

template<class T, class Ret, class... Args> 
constexpr Wrapper<T, Ret, Args...> make_wrapper(Ret(*f)(Args...)) { 
    return Wrapper<T, Ret, Args...>(f); 
} 

template<class T> 
void inspect(const T&) { 
    std::cout << __PRETTY_FUNCTION__ << std::endl; 
} 

int main() { 
    constexpr auto foobar_int = make_wrapper<Foo>(Foo::bar<int>); 
    inspect(foobar_int); 
    foobar_int(4); 

    constexpr auto foobar_double = make_wrapper<Foo>(Foo::bar<double>); 
    inspect(foobar_double); 
    foobar_double(3.8); 

    return 0; 
} 
:

아마 당신은 클래스 정보를 포함하도록 함수 포인터 주위에 래퍼를 사용할 수 있습니다