#std::visit return type deduction

7 messages · Page 1 of 1 (latest)

rare sage
#

Hi,

In my current project, I would like to use std::visit and std::variant, where the return type of std::visit should be a std::variant which template arguments should be automatically deduced by the compiler.

Here is an example:

struct Test {
 
    constexpr auto operator()(auto&& arg) {  // <--- Just using auto as return type does not work. 
          //      I guess I somehow have to specify std::variant together with variadic templates?

        using T = std::decay_t<decltype(arg)>;
        if constexpr (std::is_same_v<T, int>) {
            return float(arg);
        } else {
            return int(arg);
        }
    }
};

int main(){
    using Variant = std::variant<int, float, double>;
    auto a =  Variant(4.5f);
    auto t = std::visit(Test{}, a);
}

I want the return type of operator() in this example to be deduced as std::variant<int, float>.

I know I could explicitly write

    auto operator()(auto&& arg) -> std::variant<int, float> { ...}

But I would like to let the compiler deduce the template arguments of the return type (int and float) based on what is going on within the operator() method.
Is that even possible?

tribal spokeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

mortal berry
#

the return type in your example is being deduced, and that seems to be explicitly what you don't want!? it seems what you actually want is not return type deduction but just a particular std::variant as return type? the only way to get that is to simply specify the type. how could the compiler possibly deduce from you giving it a float as return type that, actually, what you really meant is std::variant<int, float, double>?

rare sage
#

Yes, sorry, what I actually meant was: I want the return type to be std::variant<int, float> . However, I do not want to explicitly specify int and float in that return type. I was thinking about something like this:

constexpr auto operator()(auto&& arg) -> std::variant<args...> {...}

where args is deduced from the body of that function ( int and float). But that doesn't work.

mortal berry
#

not possible

rare sage
#

Okay pwease

#

!solved