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

    [RESOLVED] How to initialize variant?

    Hi,
    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
    Posts
    399

    Re: How to initialize variant?

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

  3. #3
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: How to initialize variant?

    Code:
    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.

    Code:
    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.

    Code:
    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 http://www.cplusplus.com/reference/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 https://creativecommons.org/publicdomain/zero/1.0/ 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++23 Compiler: Microsoft VS2022 (17.6.5)

  4. #4
    Join Date
    Jun 2021
    Posts
    51

    Re: How to initialize variant?

    Hi Sirs,

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

    Name:  bug1.jpg
Views: 785
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

Featured