samedi 6 juin 2020

loop parameter pack lambda

I have a small bit of code.

I want to know if i could cut out my ProcessArg function

I would like to loop the parameter pack from inside my call function.

Im i best to use a lambda function in initializer_list or something else, if so how do i do it.

Thanks

template <class R, class Arg>
R ProcessArg(Arg&& arg) {
    std::cout << typeid(arg).name() << (std::is_reference<Arg>::value ? "&" : "") << std::endl;
    //std::cout << std::boolalpha << std::is_reference<Arg>::value << std::endl; // not always true
    return R();
}

template <typename R, typename... Args>
R CallFunction(Args&&... args) {
    std::size_t size = sizeof...(Args);
    std::initializer_list<R>{ProcessArg<R>(std::forward<Args>(args)) ...};
    return R();
}

template<typename Fn> class FunctionBase;
template<typename R, typename... Args>
class FunctionBase <R(*)(Args...)> {
public:
    FunctionBase() {}
    R operator()(Args&&... args) { // Args&& is a universal reference
        return CallFunction<R>(std::forward<Args>(args)...);
    }
};

int foo(int a, int& b) {
    std::cout << std::boolalpha << std::is_reference<decltype(a)>::value << std::endl; // falae
    std::cout << std::boolalpha << std::is_reference<decltype(b)>::value << std::endl; // true
    return a + b;
}

int main() {
    int in = 10;
    foo(1, in);

    FunctionBase<decltype(&foo)> func;
    func(1, in);
}

Aucun commentaire:

Enregistrer un commentaire