Search code examples
c++c++14generic-lambda

Extracting element with specific type from string with generic lambda


I am using c++. I have string which can contains element start with ^ and end with $. This element can be int or string.

Example:

"....^15$asdasd"-> 15
"...^bbbb$ccc"->"bbbb"

I would like to write lambda function which would do this. If I use template function the code would look like this:

template <typename T>
T getElem(string S)
{
     T retElem;
     // make calculations
     // ....
     return retElem;
}

but when I try using generic lambda I am reaching this situation :

auto getElem = [] () {
     T retElem;
     // make calculations
     // ....
     return retElem;
};

the problem is how to get type of retElem. Is there a way to use lambda in this case. I want to use generic lambda in function, where such such extraction is used. I want to to encapsulate this logic only in the function.


Solution

  • Generic lambdas have to have the argument of a (templated) type, you can't have generic lambda templatized on a non-argument. The easiest way to solve your problem is to provide a dummy argument of a given type. As in:

    template<class T>
    struct identity { using type = T; };
    ...
    auto lam = [](auto the_type) {
        using T = typename decltype(the_type)::type;
        ...
    };
    ...
    lam(identity<T>{});
    ...