-
July 15th, 2021, 07:51 PM
#1
[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.
-
July 16th, 2021, 12:38 AM
#2
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
-
July 16th, 2021, 03:20 AM
#3
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)
-
July 16th, 2021, 04:59 AM
#4
Re: How to initialize variant?
Hi Sirs,
I mistyped "," by "." but it doesn't work because of this error.
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|