Tim*_*tro 2 c++ non-member-functions c++17 stdapply std-variant
在 C++17 中,是否有一种简单的方法来 std::visit 带有重载自由函数的变体,或者我必须使用带有重载调用运算符的对象?
换句话说,是否可以添加一些简单的东西来使以下//ERROR!行编译为与该//OK!行在功能上相同?
#include<variant>
#include<iostream>
#include<list>
#include <boost/hana/functional/overload.hpp>
using boost::hana::overload;
struct A {};
struct B {};
void foo(A) { std::cout << "Got an A!\n"; }
void foo(B) { std::cout << "Got a B!\n"; }
using AorB = std::variant<A,B>;
constexpr auto foo_obj = overload(
[](A){std::cout << "Got an A!\n";},
[](B){std::cout << "Got a B!\n";});
int main() {
std::list<AorB> list{A(), B(), A(), A(), B()};
for (auto& each : list) std::visit(foo, each); // ERROR!
for (auto& each : list) std::visit(foo_obj, each); // OK!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 lambda 来处理重载:
for (auto& each : list) std::visit([](auto e){ return foo(e);}, each);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
846 次 |
| 最近记录: |