0

Can somebody explain in simple terms the below template code syntax which I found while learning C++ 17 std::visit.

#include <iostream>
#include <string>
#include <variant>

template<typename... Targs>
struct VariantType : Targs... {
    using Targs::operator()...;
};

template<typename... Targs>
VariantType(Targs...) -> VariantType<Targs...>;

int main() {
    std::variant<int, double, std::string> var;
    var = "Hello, world!";
    std::visit(
        VariantType {
            [] (int i) { std::cout << "int: " << i << std::endl; },
            [] (double d) { std::cout << "double: " << d << std::endl; },
            [] (const std::string& str) { std::cout << "std::string: " << str << std::endl; }
        }, var
    );
}
Harry
  • 2,177
  • 1
  • 19
  • 33
  • 2
    Which bit is are you asking about? There are dupe targets for all the things in this code. – NathanOliver Jun 10 '22 at 11:58
  • @NathanOliver the template code that is outside `main` function. I've never seen such syntax and I'm not getting what's going on in that part. – Harry Jun 10 '22 at 12:00
  • do you mean `template VariantType(Targs...) -> VariantType;`, thats a deduction guide (https://en.cppreference.com/w/cpp/language/class_template_argument_deduction) or also all the rest outside of `main` ? – 463035818_is_not_an_ai Jun 10 '22 at 12:02
  • @463035818_is_not_a_number rest outside `main` – Harry Jun 10 '22 at 12:03
  • Also see: https://en.cppreference.com/w/cpp/language/class_template_argument_deduction – NathanOliver Jun 10 '22 at 12:03
  • in that case you went to fast. `std::variant` itself is a variadic template. Before you understood that `std::visit` will be puzzling – 463035818_is_not_an_ai Jun 10 '22 at 12:04
  • i was looking for a dupe about variadic templates. Didnt find a good one, but this might be worth a read https://stackoverflow.com/questions/17652412/what-are-the-rules-for-the-token-in-the-context-of-variadic-templates – 463035818_is_not_an_ai Jun 10 '22 at 12:06
  • 2
    The second dupe target that I just added will break the entire thing down for you. – NathanOliver Jun 10 '22 at 12:08

0 Answers0