CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2021

    [RESOLVED] How to initialize variant?

    I'm having a hard time initializing the variable as follows:
    using mytype=std::variant<int, double, int>;

    I tried this but it doesn't work.
    mytype k{1,1.124,2};

    I've seen this post, but it doesn't seem to be clear.
    How do I fix the above code?
    Thanks you!
    Last edited by Dang.D.Khanh; July 16th, 2021 at 04:52 AM.

  2. #2
    Join Date
    Jan 2009

    Re: How to initialize variant?

    I guess you have a typo:
    mytype k{1,1.124,2};    // last comma was a point, not comma

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012

    Re: How to initialize variant?

    using mytype=std::variant<int, double, int>;
    No. You are specifying int twice. You only specify the different types that the variant might hold, not their order or number.

    mytype k{1,1.124.2};
    No. A variant can only hold one value at a time which has to one of the specified types.

    using mytype=std::variant<int, double>;
    mytype k1 {1};
    mytype k2 {3.4};
    mytype ka[3] {1, 1.124, 2};
    If you want to store the values 1 1.124 2 as a one variable, consider using either a struct or a tuple
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2022 (17.0.1)

  4. #4
    Join Date
    Jun 2021

    Re: How to initialize variant?

    Hi Sirs,

    I mistyped "," by "." but it doesn't work because of this error.

    Name:  bug1.jpg
Views: 67
Size:  30.7 KB

    but when Changing the type to avoid duplicate or using struct both works fine for me now.

    Thanks for clarifying!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width