Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 根据is_integer将强制转换为int或float_C++_Templates_Typedef - Fatal编程技术网

C++ 根据is_integer将强制转换为int或float

C++ 根据is_integer将强制转换为int或float,c++,templates,typedef,C++,Templates,Typedef,我有一些类型T,在某些情况下可能是,例如char,但我想输出它的整数值,而不是字符。为此,应具备以下条件: typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType; os << static_cast< FormatType >( t ); typedef if_<std::numeric_limits< T >::is_integer, int,

我有一些类型
T
,在某些情况下可能是,例如
char
,但我想输出它的整数值,而不是字符。为此,应具备以下条件:

typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType;
os << static_cast< FormatType >( t );
typedef if_<std::numeric_limits< T >::is_integer, int, double>::type FormatType;

os << static_cast< FormatType >( t );

尝试使用积分促销:

os << +t;
os
我错过了什么

您正在尝试将类型用作表达式。C++根本不允许这样做。您可以通过元编程使用所谓的“编译时
if
”。例如,我认为Boost提供了以下功能:

typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType;
os << static_cast< FormatType >( t );
typedef if_<std::numeric_limits< T >::is_integer, int, double>::type FormatType;

os << static_cast< FormatType >( t );
typedef如果\是\整数,int,double>::type FormatType;
os(t);

另一方面,第二个解决方案运行良好,编译器将发现其中一个分支永远不可能为真,并将其消除。因此,在这两种情况下,性能将是相同的(事实上,应该生成完全相同的代码)。

gcc接受它,但不确定其他代码:

template<bool Expression, typename TrueResult, typename FalseResult>
  class conditional_type;

template<typename TrueResult, typename FalseResult>
class conditional_type<1, TrueResult, FalseResult> {
public:
    typedef TrueResult R;
};

template<typename TrueResult, typename FalseResult>
class conditional_type<0, TrueResult, FalseResult> {
public:
    typedef FalseResult R;
};

typedef conditional_type<std::numeric_limits<T>::is_integer,int,float>::R FormatType;
模板
类条件类型;
样板
类条件类型{
公众:
打字机;
};
样板
类条件类型{
公众:
打字机;
};
typedef条件类型::R FormatType;

这是非常标准的模板专门化,所有现代编译器都接受这一点。你为什么用
1
0
而不是
true
false
。问题是,为什么滥用C++有弱类型系统的事实?@康拉德和其他人可能同样倾向于质疑为什么我选择了<代码>类< /C> >,而不是<代码>结构> <代码>。有些人选择
NULL
,有些人则更喜欢
0
。我不认为这是虐待,而是偏好(每个人都有)。每个人都应该足够了解这些基础知识,以免明显影响可读性。但是为了回答你的问题:我想我的例子中的变化的根源是(在c++的范围之外)有几个布尔类型和常量——当涉及到编写代码时,我更喜欢简单。基于我所调用的代码,我不想在我的(cont)代码库中使用6种不同的true和false。所以我只保留了类型,省略了命名常量的使用。是的,如果真与假的定义改变了,我会有很多代码需要修改。@Justin:这就是“你写的方式”?这很愚蠢。
true
false
的定义永远不会改变,但使用它们的好处是它们完全按照它们所说的做,并且它们具有预期的类型。顺便说一句,除了前者无效之外,它们是等价的。:)太晦涩了,不能按原样使用,伊姆霍。我会将其封装在一个正确命名的函数中,以明确其意图。康拉德:你的函数需要模板化,我想我们应该回到最初的问题开始的地方。我不认为它是晦涩难懂的,尽管在它的用法旁边加上一个小注释可能不是一个坏主意。@Tomak:我接受了Konrad的回答,因为它直接解决了这个问题,但我实际上在我的代码中使用了你的方法,所以我希望我能给出+1以上;我还添加了一条评论来传递知识:)@Dave::)很高兴你找到了解决方案。