Using std::visit with variadic template struct

Viewed 927

I was trying to understand the following example which I got from http://en.cppreference.com/w/cpp/utility/variant/visit

#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);
    }
}

Can someone please explain how this overloaded struct works? Especially what I didn't understand is the following declaration.

template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

Without this declaration, the compiler issues the following error messages.

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

Purpose: learning

1 Answers
Related