0

I am working with tuples and auto, and I am facing the following errors. What am I doing wrong?

#include <iostream>
#include <string>
#include <tuple>

struct Custom
{
    enum {INT, STRING} tags;
    union dummy {
        std::string s;
        uint64_t i;
    };
};

int main()
{
    std::tuple<std::string, uint64_t> xs = {"hello World", 45};
    auto [str, i] = xs;
    std::cout<<str<<" "<<i<<"\n"; // works fine

    Custom c1 = {Custom::INT, 45}; // error: too many initializers for 'Custom'

    std::tuple<std::string, Custom> xs1 = {"hello World", { Custom::Tag::INT ,45}}; // error: too many initializers for 'Custom'
    auto [p1, p2] = xs1; // error: cannot be referenced -- it is a deleted function
}
kishoredbn
  • 2,007
  • 4
  • 28
  • 47
  • 4
    Side note: a `std::string` in a `union` can get really ugly. It needs special care and feeding. Can we assume `std::variant` is not available? – user4581301 May 06 '20 at 15:49
  • 2
    Putting a `std::string` in a union basically breaks the union. You'll need to add a lot of code to get the union working again which basically gives you `std::variant`. – NathanOliver May 06 '20 at 15:50
  • @user4581301 can you share some link to read on this? or say little more on this? – kishoredbn May 06 '20 at 15:50
  • 3
    @kishoredbn see: https://stackoverflow.com/questions/40106941/is-a-union-members-destructor-called – NathanOliver May 06 '20 at 15:53
  • Yeah, I'll stop typing now. I think that covered everything I was going to say and a lot more. – user4581301 May 06 '20 at 15:55
  • Aggregate initialization's still going to be a problem. Kudos for trying something I don't think I've even tried. – user4581301 May 06 '20 at 16:03
  • I feel hopeless with C++. I don't understand this language. – kishoredbn May 06 '20 at 16:08
  • 2
    @kishoredbn Don't feel too bad. Most of us don't. C++ really doesn't like type punning, so there are a lot of rules in the language to try and stop you from doing that which makes unions hard to deal with for things other than "POD" types. – NathanOliver May 06 '20 at 16:10
  • 1
    @kishoredbn: "*I don't understand this language.*" You don't really *need* to. There are just some features that should be avoided by those who don't aren't doing something very low-level. `union`s are one of those features; this is one reason why we have `variant`. – Nicol Bolas May 06 '20 at 16:41

0 Answers0