Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::invoke of a function template/lambda fails

How can I get this working? (C++17/20)
Note: I have to use std::invoke here because in the real code, the only guarantee I have is that this callable is invokable.

#include <bits/stdc++.h> // to include everything

int main() {
    const auto func = [&]<typename T>(const std::string& h) {
        T t;
        std::cout << t << " " << h << "\n";
    };
    std::invoke(func<std::string>, std::string("Hello"));
}

Error:

<source>:17:33: error: expected primary-expression before '>' token
   17 |     std::invoke(func<std::string>, std::string("Hello"));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As mentioned in the comment func is not a function template, but rather has a templated operator().

One way to use std::invoke the way you attempted, would be to actually change func into a function template:

#include <string>
#include <iostream>
#include <functional>

template <typename T>
void func(const std::string& h)
{
    T t;
    std::cout << t << " " << h << "\n";
}

int main() 
{
    std::invoke(func<std::string>, std::string("Hello"));
}

Live demo – Godbolt

A side note: better to avoid #include <bits/stdc++.h>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading