如何自动添加文字定义,基于单个用户定义的文字? [英] How to automatically add literal definitions, based on a single user-defined literal?
问题描述
C ++ 11
提供用户定义的文字。我刚刚开始与他们一起玩,这让我想知道是否可以自动添加所有 SI乘法器到单个字面量我定义?
C++11
offers user-defined literals. I've just started to play around with them, which made me wonder whether it would be possible to automatically add all SI multipliers to a single literal I define?
例如,如果我定义
Length operator "" _m(long double m) {
return Length(m); // Length in meters
}
其中长度
是一些 Units
基类的子类,我想有一个自动 添加的机制 a href =http://www.boost.org/doc/libs/1_53_0/libs/utility/operators.htm =nofollow> boost运算符)所有文本的SI乘数,返回 Length
:
where Length
is a subclass of some Units
base class, I would like to have a mechanism to automatically add (in the same spirit as boost operators) SI multipliers for all literals that return a Length
:
// these are added automatically when defining the literal "_m":
// Length in:
Length operator "" _Ym(long double Ym); // Yottameters
Length operator "" _Zm(long double Zm); // Zetameters
... // ...
... // ...
Length operator "" _km(long double km); // kilometers
Length operator "" _mm(long double mm); // millimeters
... // ...
... // ...
Length operator "" _zm(long double zm); // zeptometers
Length operator "" _ym(long double ym); // yoctometers
就我所见,除了一些宏魔法,自动执行此操作,因为所有用户定义的文本都需要显式的定义。
As far as I could see, aside from perhaps some macro magic, there is no way to do this automatically since all user-defined literals need an explicit definition.
..或者我可以忽略某些东西吗?
..or am I overlooking something?
推荐答案
我不认为有一种方法可以做到你所要求的没有奇怪的宏。这是我可以得到的:
I do not think there is a way to do exactly what you are asking for without "bizarre macros". This is as far as I could get:
template<typename T, T (*op)(long double)>
struct SI
{
// ...
constexpr static T micro = op (.000001);
constexpr static T milli = op (.001);
constexpr static T kilo = op (1000);
constexpr static T mega = op (1000000);
// ...
};
struct Length
{
constexpr Length(long double d) : _d(d) { }
constexpr operator long double() { return _d; }
long double _d;
};
constexpr Length operator "" _m(long double m) {
return Length(m);
}
typedef SI<Length, ::operator "" _m> SI_Length;
int main()
{
constexpr Length l = 3 * SI_Length::kilo;
static_assert(l == 3000, "error");
}
如果允许使用奇怪的宏,则应执行以下操作:
If bizarre macros are allowed, then something like the following should do the job:
#define DEFINE_SI_MULTIPLIERS(T, unit) \
constexpr T operator "" _u ## unit(long double m) \
{ return ::operator "" _ ## unit(0.000001 * m); } \
constexpr T operator "" _m ## unit(long double m) \
{ return ::operator "" _ ## unit(0.001 * m); } \
constexpr T operator "" _k ## unit(long double m) \
{ return ::operator "" _ ## unit(1000 * m); } \
// ...
DEFINE_SI_MULTIPLIERS(Length, m)
int main()
{
constexpr Length l = 3.0_km;
static_assert(l == 3000, "error");
}
这篇关于如何自动添加文字定义,基于单个用户定义的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!