How to pass a function pointer that points to constructor?

前端 未结 7 1977
陌清茗
陌清茗 2020-11-29 06:45

I\'m working on implementing a reflection mechanism in C++. All objects within my code are a subclass of Object(my own generic type) that contain a static member datum of ty

相关标签:
7条回答
  • 2020-11-29 07:10

    Using variadic templates you can create a wrapper which will turn the constructor into a functor.

    #include <utility>
    
    template <typename T>
    struct BindConstructor{
        template<typename... Args>
        T operator()(Args...args)const{
            return T(std::forward<Args>(args)...);
        }
    };
    
    
    struct Foo {
        Foo(int a, int b):a(a),b(b){}
        int a;
        int b;
    };
    
    template <typename Fn>
    auto Bar(Fn f){
        return f(10,20);
    }
    
    int main(){
        Foo foo = Bar(BindConstructor<Foo>());
    }
    

    https://godbolt.org/z/J6udk7

    0 讨论(0)
提交回复
热议问题