0

Can PODs have implicit conversion, both to and from the POD, and still remain a POD?

struct POD
{
   int a;
   
#ifdef __cplusplus
   POD(int _a) : a(_a) {}
   operator int() const { return a; }
#endif
};

note that I need Data to be POD in c++ as well, I want implicit conversions only as a syntactic sugar. So I need the optimizations that a compiler would do with a POD since this is used in hot path of the program.

273K
  • 29,503
  • 10
  • 41
  • 64
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118

2 Answers2

4

By providing a converting constructor you removed the implicit default constructor and made the struct non POD. Return the default constructor and you get a POD.

struct POD
{
   int a;
   
#ifdef __cplusplus
   POD() = default;
   POD(int _a) : a(_a) {}
   operator int() const { return a; }
#endif
};
273K
  • 29,503
  • 10
  • 41
  • 64
1

You class is not POD since it does not have a (trivial) default constructor. If you add one and make sure it's trivial, the class becomes POD.

Live demo: https://godbolt.org/z/7EcE6bxo8

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93