[편집 : 미터/야드를 foo/bar로 변경했습니다. 이것은 미터를 야드로 변환하는 것이 아닙니다. ]유형을 스칼라에 연결하는 기본 메커니즘은 무엇입니까?
유형을 double
과 같은 스칼라에 연결하는 가장 좋은 방법은 무엇입니까? 일반적인 유스 케이스는 측정 단위입니다 (그러나 실제 구현을 찾고 있지는 않습니다, boost has one). 정말 사건인가요
template <typename T>
struct Double final
{
typedef T type;
double value;
};
namespace tags
{
struct foo final {};
struct bar final {};
}
constexpr double FOOS_TO_BARS_ = 3.141592654;
inline Double<tags::bar> to_bars(const Double<tags::foo>& foos)
{
return Double<tags::bar> { foos.value * FOOS_TO_BARS_ };
}
static void test(double value)
{
using namespace tags;
const Double<foo> value_in_foos{ value };
const Double<bar> value_in_bars = to_bars(value_in_foos);
}
:
이 같은 간단한 것처럼 보일 것? 아니면 숨겨진 복잡성이나이 접근법에 대한 다른 중요한 고려 사항이 있습니까?
이 거의 복잡성 또는 오버 헤드를 추가하지 않고
inline double foos_to_bars(double foos)
{
return foos * FOOS_TO_BARS_;
}
훨씬 우수, 멀리 보인다.
간단하지만 모든 합법적 인 변환을 직접 프로그래밍해야합니다. – StoryTeller
이것은 [* 사용자 정의 리터럴 *] (http://en.cppreference.com/w/cpp/language/user_literal)에 대한 좋은 사례 인 것 같습니다. –
또한 std :: ratio의 경우 – xvan