0

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"));
wohlstad
  • 12,661
  • 10
  • 26
  • 39
Happytreat
  • 139
  • 7

3 Answers3

2

lambda is not template, but its operator() is.

As T is not deducible, you might write:

std::invoke([&](const std::string &s) { func.operator()<std::string>(s); },
            std::string("Hello"));

or more "simply":

func.operator()<std::string>("Hello");

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

The problem is that your lambda 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>.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • Please explain the downvote. If there's something wrong in my answer I'll be glad to understand it. – wohlstad Aug 30 '23 at 18:02
0

One way is to pass the pointer-to-member function (&decltype(f)::operator()<int>), then give it the object (f) and the arguments(std::string)

#include "bits/stdc++.h"

int main() {
    const auto f = []<typename T>(std::string) -> void {};
    std::invoke(&decltype(f)::operator()<int>, f, "hello");
}
weineng
  • 146
  • 6
  • [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – wohlstad Jun 30 '23 at 06:03