lundi 29 mars 2021

How to pass a lambda to a template paramater

I'm trying to define a function func, which returns a std::string.

template<typename T = std::string, template<typename> typename F = decltype([](const T &t){return t;})>
std::string func(const T &t){
    F f;
    return f(t);
}

As you see, what I'm trying to do is to pass a lambda as the template paramater so that I can call the function func like this:

func<int, decltype([](int a){return std::to_string(a);})>(2);

Also, I set the values by default for the template parameters so that I can call it like this:

func<>("abc");

However, the code above gave me an error:

<source>:39:54: error: expected unqualified-id before 'decltype'
   39 | template<typename T, template<typename> typename F = decltype([](const T &t){return t;})>
      |                                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:39:54: error: invalid default argument for a template template parameter
<source>:39:54: error: expected '>' before 'decltype'

BTW, the version of my C++ is C++11.

Aucun commentaire:

Enregistrer un commentaire