prydain
prydain

Reputation: 365

Do two user defined conversions

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.

Upvotes: 1

Views: 49

Answers (1)

sehe
sehe

Reputation: 392833

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

Upvotes: 3

Related Questions