jeudi 27 octobre 2016

c++11 segmentation fault while playing with variadic templates

So I was Playing around with c++11 Varidiacs, and I wanted to create a thing called CallClass, basically a class that warps a function, for later call,when all variables are set(truly I have No Idea If It can Be Useful):

#include <tuple>

template <typename OBJ,typename F,typename... VARGS>
class CallClass
{
    public:

        CallClass(OBJ& object,F callFunction)
        :_object(&object),_func(callFunction)
        { }

        CallClass(const CallClass& other)
        :_func_args(other._func_args)
        ,_object(other._object)
        ,_func(other._func)
        { }

        template <size_t INDEX>
        auto get(){ return std::get<INDEX>(_func_args); }

        template <size_t INDEX,typename T>
        void set(const T& val){ std::get<INDEX>(_func_args) = val; }

        template <size_t INDEX,typename T>
        void set(T&& val){ std::get<INDEX>(_func_args) = val; }

        auto Call()
        {
            //throws segmentation Fault Here
            return InnerCall<0>(_func_args);
        }

        virtual ~CallClass() {}

    protected:

    private:
        std::tuple<VARGS...> _func_args;
        OBJ* _object;
        F _func;

        template <size_t INDEX,typename... ARGS>
        auto InnerCall(std::tuple<VARGS...>& tup,ARGS... args)
        {
            auto arg = std::get<INDEX>(tup);

            return InnerCall<INDEX + 1>(tup,args...,arg);
        }

        template <size_t INDEX,VARGS...>
        auto InnerCall(std::tuple<VARGS...>& tup,VARGS... args)
        {
            return (_object->*_func)(args...);
        }
};

Now when I try to compile(compiling using IDE:code::blocks, configured to use MINGW On windows ), it prints Compiler:Segmentation Fault, anybody any Ideas?

Usage:

class obj{
public:
    obj(int a)
    :_a(a)
    { }

    virtual ~obj() {}

    int add(int b,int c){
        return _a + b + c;
    }

private:
    int _a;
};

int main(){
obj ob(6);
CallClass<obj,decltype(obj::add),int,int> callAdd(ob,obj::add);

    callAdd.set<0,int>(5);
    callAdd.set<1,int>(7);
    cout << "result is " << callAdd.Call() << endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire