-1

how can i declare a variable with different types in C++

 struct maxKernelBetTwoVec
 {
     size_t  Elem1;
     double Elem2;
  };

so Elem2 can be int, or double, or string.

  • 3
    It depends on what you are doing. Why do you want that? – Galik Apr 06 '17 at 03:40
  • 1
    You must use a union – eyllanesc Apr 06 '17 at 03:42
  • 1
    read this: http://stackoverflow.com/questions/252552/why-do-we-need-c-unions – eyllanesc Apr 06 '17 at 03:42
  • While a union is good, and probably the best answer here, you could always just declare a `void * Elem2` and treat it how you like, allocating the memory you need and then deleting that and reallocating it to suit another type of variable. Although personally that just seems like a lot of work, I'd rather just create multiple variables (kinda how unions work). – Andria Apr 06 '17 at 03:46
  • 4
    This sounds like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – R Sahu Apr 06 '17 at 03:56
  • 1
    Several solutions. Need more more information about how you plan to use this in order to provide a worthwhile answer. – user4581301 Apr 06 '17 at 04:05
  • @ eyllanesc, @ chbchb55 thnx that help – user3406305 Apr 06 '17 at 04:11

1 Answers1

0

You could use a union, but they are hard to use correctly and safely. A far better option is to use a std::variant:

struct maxKernelBetTwoVec
{
    size_t Elem1;
    std::variant<int, double, std::string> Elem2;
};

Unfortunately, std::variant is only available in C++17. If you can't yet use std::variant, you can use boost::variant instead.

Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38