0

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.

Vladimir Yanakiev
  • 1,240
  • 1
  • 16
  • 25

2 Answers2

2

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>{});
...
SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • SergayA this is good suggestion. My purpose is to use lambda in a function where such code is repeated. I will fix this in my question. Your suggestion is OK if "struct identity" is in namespace scope. plus 1 – Vladimir Yanakiev Aug 04 '17 at 15:07
  • @VladimirYanakiev yes, identity has to be in namespace scope, for obvious reasons. On any rate, this is very valueable tool for anybody doing serious metaprogramming :D – SergeyA Aug 04 '17 at 15:09
-3

Since it is C++14, you can use compiler type inference through decltype(auto):

int i = []() -> decltype(auto) {
    return 1;
}();
noavarice
  • 15
  • 3