英文:
std::invoke of a function template/lambda fails
问题
How can I get this working? (C++17/20)
注意:我必须在这里使用 std::invoke
,因为在实际代码中,我唯一的保证是这个可调用对象是可以调用的。
#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"));
英文:
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"));
答案1
得分: 2
lambda不是模板,但它的operator()
是。
由于T
无法推断出来,你可以这样写:
std::invoke([&](const std::string &s) { func.operator()<std::string>(s); },
std::string("Hello"));
或更"简单"地:
func.operator()<std::string>("Hello");
英文:
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");
答案2
得分: 0
问题在于您的lambda函数func
不是一个函数模板,而是具有模板化的operator()
。
使用您尝试的方式使用std::invoke
的一种方法是实际上将func
更改为函数模板:
#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"));
}
一点额外说明: 最好避免使用#include <bits/stdc++.h>。
英文:
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"));
}
A side note: better to avoid #include <bits/stdc++.h>.
答案3
得分: 0
一种方法是传递指向成员函数的指针(&decltype(f)::operator()<int>
),然后给它传递对象(f
)和参数(std::string
)
#include "bits/stdc++.h"
int main() {
const auto f = []<typename T>(std::string) -> void {};
std::invoke(&decltype(f)::operator()<int>, f, "hello");
}
英文:
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");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论