做两个用户定义的转换
Do two user defined conversions
基本上我想做的是这样的:
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)
我无法更改目标结构,因为有代码希望它成为 POD。我现在 C++ 标准说它只允许使用一个用户定义的转换,但也许有一些魔术可以在这里使用而不是使用函数。
target make_target(float a){ return target{(int)a*1024}; }
target t = make_target(1.0f);
可以,但很烦人,因为我真正做的就是将浮点数乘以 1024。
您可以在它保持 POD 时添加构造函数:
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";
}
版画
3215
基本上我想做的是这样的:
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)
我无法更改目标结构,因为有代码希望它成为 POD。我现在 C++ 标准说它只允许使用一个用户定义的转换,但也许有一些魔术可以在这里使用而不是使用函数。
target make_target(float a){ return target{(int)a*1024}; }
target t = make_target(1.0f);
可以,但很烦人,因为我真正做的就是将浮点数乘以 1024。
您可以在它保持 POD 时添加构造函数:
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";
}
版画
3215