0
#include <iostream>
#include <variant>
using namespace std;
 
int main()
{
    variant<int, float> var{0.23};
    if(holds_alternative<float>(var)){
        if(var.index() == 1){
            cout << get<float>(var) << endl;
        }
    }
    
    return 0;
}

The initialization should work but instead it gives the following error:

main.cpp: In function 'int main()': main.cpp:7:33: error: no matching function for call to 'std::variant<int, float>::variant()'

I'm not sure if I made a mistake in the code.

2 Answers 2

2

0.23 is double. You should use 0.23f, which is float, instead.

Sign up to request clarification or add additional context in comments.

Comments

1

The initialization failed because of the narrowing conversion inside the curly braces. so use

   variant<int, float> var{0.23f};

instead.

Note that 0.23 is a double literal, not a float one.

See demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.