1

Basically what i want to do is something like this:

struct target {
    int somevalue;
}
struct target_wrapper {
    target t;
    target_wrapper(float v) : t(target{(int)v * 1024}){}
    operator target() { return t; }
}

target t = 1.0f; // would be called as t = (target)((target_wrapper)1.0f)

I can not change the target structure since there is code expecting it to be a POD. I now that the C++ standard says its only allowed to use one user defined conversion but maybe there is some magic trick one could use here instead of using a function.

target make_target(float a){ return target{(int)a*1024}; }

target t = make_target(1.0f);

Would work but it is rather annoying since all I really do is multiply the float by 1024.

prydain
  • 365
  • 3
  • 11
  • I'd suggest to add parens `(int)(v * 1024)` just to make sure it doesn't do `int(v)*1024` there. Of course, there's really no excuse to not use `static_cast` here anyways :) – sehe Jan 20 '15 at 22:49

1 Answers1

3

You can add a constructor while it stays POD:

Live On Coliru

struct target {
    int somevalue;
    target() = default;
    constexpr target(float f) : somevalue(static_cast<int>(1024*f)) {}
};

#include <type_traits>
#include <boost/type_traits.hpp>
static_assert(std::is_pod<target>::value,   "expected to be POD");
static_assert(boost::is_pod<target>::value, "expected to be POD");

#include <iostream>

int main() {
    target t = 3.14f;
    std::cout << t.somevalue << "\n";
}

Prints

3215
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Thank you very much this seems to work like it should. Could you explain the "target() = default;" part, I guess its the same as "target(){}" but I'm not to familiar with the newer C++ standards. – prydain Jan 20 '15 at 22:51
  • It explicitly instructs the compiler to _still_ generate the default constructor. This is _different_ from supplying a custom default constructor (which would [break podness](http://coliru.stacked-crooked.com/a/5ab88537a81e9b26)), even though in this case the intended effect would be exactly the same. – sehe Jan 20 '15 at 22:52
  • [If you like graphical, tabular results, slide 28 from github.com/HowardHinnant/presentations/blob/master/accu_2014/…](http://stackoverflow.com/questions/24342941/what-are-the-rules-for-automatic-generation-of-move-operations#comment37634197_24342941) – sehe Jan 20 '15 at 22:54