根据 is_integer 转换为 int 或 float
我有一些类型 T
,在某些情况下可能是,例如 char
,但我想输出它的整数值,而不是字符。为此,有以下内容:
typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType;
os << static_cast< FormatType >( t );
但是,这无法编译,并指出“错误 C2275:'int':非法使用此类型作为表达式
”。在 int
和 float
前面加上 typename
并不能解决问题。我在这里缺少什么?
我认为以下内容是等效的:
if( std::numeric_limits< T >::is_integer )
{
os << static_cast< int >( t );
}
else
{
os << static_cast< float >( t );
}
I have some type T
, and in some cases it may be, for example char
, but I want to output its integral value, not the character. For this is have the following:
typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType;
os << static_cast< FormatType >( t );
However this fails to compile, stating "error C2275: 'int' : illegal use of this type as an expression
". Prefixing int
and float
with typename
does not revolve the issue. What am I missing here?
The following, which I believe is equivalent, works:
if( std::numeric_limits< T >::is_integer )
{
os << static_cast< int >( t );
}
else
{
os << static_cast< float >( t );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用整型提升:
对于整型,您将获得一个
int
;如果是原始浮点类型,则为您的原始浮点类型。Try using integral promotion:
You'll get an
int
out of it for an integral type, or your original floating-point type if it was one.gcc 接受它,不确定其他的:
gcc accepts it, not sure about others:
您正在尝试使用类型作为表达式。 C++ 根本不允许这样做。您可以通过元编程使用所谓的“编译时
if
”。例如,我相信 Boost 提供了以下功能:另一方面,你的第二个解决方案运行良好,编译器会发现其中一个分支永远不可能为真,并消除它。因此,两种情况下的性能都是相同的(事实上,应该生成完全相同的代码)。
You are trying to use types as expressions. C++ simply doesn’t allow this. You can instead use so-called “compile-time
if
” via metaprogramming. For example, I believe Boost offers the following:On your other hand, your second solution works well, and the compiler will figure out that one of the branches can never be true, and eliminate it. So the performance will be the same in both cases (in fact, the exact same code should be generated).