2017-12-03 11 views
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; 
} 

たぶん、あなたは、クラス情報を含めるように関数ポインタの周りにラッパーを使用することができます

関連する問題