Tôi đã cố gắng tìm hiểu các ví dụ sau đây mà tôi nhận được từ http://en.cppreference.com/w/cpp/utility/variant/visitSử dụng std :: thăm với mẫu variadic struct
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
using var_t = std::variant<int, long, double, std::string>;
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
// what is this declaration imply???
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
std::vector<var_t> vec = {10, 15l, 1.5, "hello"};
for (auto& v: vec) {
std::visit(overloaded {
[](auto arg) { std::cout << arg << '\n'; },
[](double arg) { std::cout << std::fixed << arg << '\n'; },
[](const std::string& arg) { std::cout << std::quoted(arg) << '\n'; },
}, v);
}
}
Có thể ai đó xin vui lòng giải thích cách này quá tải công trình struct? Đặc biệt những gì tôi không hiểu là tuyên bố sau đây.
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
Nếu không có tuyên bố này, trình biên dịch sẽ đưa ra các thông báo lỗi sau.
main.cpp: In function 'int main()':
main.cpp:26:9: error: class template argument deduction failed:
}, v);
^
main.cpp:26: confused by earlier errors, bailing out
Mục đích: học tập
Có [đề xuất] (http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0051r2.pdf) để thêm nội dung tương tự vào thư viện chuẩn như 'std :: quá tải' và [video dài 5 phút] (https://www.youtube.com/watch?v=1gNzhE-Tn40&list=PLs3KjaCtOwSZ2tbuV1hx8Xz-rFZTan2J1&index=50) về việc triển khai video này. –