Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the types of a lambda in c++0x?

How is it possible to access the types of the parameters of a lambda function in c++? The following does not work:

template <class T> struct capture_lambda {
};

template <class R, class T> struct capture_lambda<R(T)> {
    static void exec() {
    }
};

template <class T> void test(T t) {
    capture_lambda<T>::exec();
}

int main() {
    test([](int i)->int{ return 0; });
}

The above does not compile, because the compiler chooses the template prototype instead of the specialization.

Is there a way to do the above?

What I am actually trying to achieve is this: I have a list of functions and I want to select the appropriate function to invoke. Example:

template <class T, class ...F> void exec(T t, F... f...) {
    //select the appropriate function from 'F' to invoke, based on match with T.
}

For example, I want to invoke the function that takes 'int':

exec(1, [](char c){ printf("Error"); }, [](int i){ printf("Ok"); });
like image 413
axilmar Avatar asked Nov 05 '22 07:11

axilmar


1 Answers

This isn't possible, lambda functions are syntactic sugar for creating function objects not actual functions. This means that the template is accepting a class, and classes don't have the concept of argument type.

Also keep in mind that a general function object can have any number of overloaded operator()s.

like image 200
Motti Avatar answered Nov 09 '22 09:11

Motti