I want to get the active value in a std::variant without knowing which one is active. I thought i could write a template visitor and use std::visit but it doesn't work.
#include <variant> #include <string> #include <iostream> struct Visit_configuration { template<typename Data_type> Data_type operator()(Data_type& t) const { return t; } }; int main() { std::variant<int, std::string> v; v = "hello"; std::cout << std::visit(Visit_configuration(), v); // expect "hello" std::cin.get(); } MSVC doesn't compile and throws:
error C2338: visit() requires the result of all potential invocations to have the same type and value category (N4741 23.7.7 [variant.visit]/2).
note: see reference to function template instantiation 'int std::visit&,0>(_Callable &&,std::variant &)' being compiled
So how to fix this?
edit: I want to use the obtained value maybe also for other so putting cout in the template isn't what im looking for.
vwill always contain astd::string, and a good static analysis tool will could also make that determination, it's beyond what a compiler is required to be able to deduce. Notably,visn'tconstexprand the compiler doesn't understand whatvcontains at compile time any more than if you depended on user input. So the return type ofstd::visitcan't be determined.operator()output the value, rather than trying to return it from the visitor so the caller can output it. For example:std::visit([](auto&& arg){std::cout << arg;}, v);