C++ 提升业力-非消耗谓词
我需要打印一个std::复数,但如果它等于零,则省略虚部。所以我有一个规则,有两个结果:C++ 提升业力-非消耗谓词,c++,boost,boost-spirit,boost-spirit-karma,C++,Boost,Boost Spirit,Boost Spirit Karma,我需要打印一个std::复数,但如果它等于零,则省略虚部。所以我有一个规则,有两个结果: karma::rule<OutputIterator, std::complex<double>()> complexRule = '(' << double_ << ", " double_ << ')' | double_ << omit[double_]; karma::规则复合体规则= (“我个人不想把它改编
karma::rule<OutputIterator, std::complex<double>()> complexRule =
'(' << double_ << ", " double_ << ')'
| double_ << omit[double_];
karma::规则复合体规则=
(“我个人不想把它改编成一个序列(我不知道你一开始是怎么把它改编成两个元素的融合序列的)
但是,它不会是泛型的(因此您必须对不同类型的参数使用单独的自适应(float
,double
,long double
,boost::multiprecision::number
等)
这似乎是Spirit的一份工作:
namespace boost { namespace spirit { namespace traits {
template <typename T>
struct extract_from_attribute<typename std::complex<T>, boost::fusion::vector2<T, T>, void>
{
typedef boost::fusion::vector2<T,T> type;
template <typename Context>
static type call(std::complex<T> const& attr, Context& context)
{
return { attr.real(), attr.imag() };
}
};
} } }
输出:
(123.0, 4.0)
123.0
(123.0, inf)
nan
(123.0, -1.0)
非常感谢!karma::duplicate解决了这个问题。关于使用自定义点的建议也很好,看起来绝对值得一看。
namespace boost { namespace spirit { namespace traits {
template <typename T>
struct extract_from_attribute<typename std::complex<T>, boost::fusion::vector2<T, T>, void>
{
typedef boost::fusion::vector2<T,T> type;
template <typename Context>
static type call(std::complex<T> const& attr, Context& context)
{
return { attr.real(), attr.imag() };
}
};
} } }
rule =
'(' << karma::double_ << ", " << karma::duplicate [ !karma::double_(0.0) << karma::double_ ] << ')'
| karma::double_ << karma::omit [ karma::double_ ];
#include <boost/spirit/include/karma.hpp>
#include <complex>
namespace boost { namespace spirit { namespace traits {
template <typename T>
struct extract_from_attribute<typename std::complex<T>, boost::fusion::vector2<T, T>, void>
{
typedef boost::fusion::vector2<T,T> type;
template <typename Context>
static type call(std::complex<T> const& attr, Context& context)
{
return { attr.real(), attr.imag() };
}
};
} } }
namespace karma = boost::spirit::karma;
int main()
{
karma::rule<boost::spirit::ostream_iterator, boost::fusion::vector2<double, double>()>
static const rule =
'(' << karma::double_ << ", " << karma::duplicate [ !karma::double_(0.0) << karma::double_ ] << ')'
| karma::double_ << karma::omit [ karma::double_ ];
std::vector<std::complex<double>> const values {
{ 123, 4 },
{ 123, 0 },
{ 123, std::numeric_limits<double>::infinity() },
{ std::numeric_limits<double>::quiet_NaN(), 0 },
{ 123, -1 },
};
std::cout << karma::format_delimited(*rule, '\n', values);
}
(123.0, 4.0)
123.0
(123.0, inf)
nan
(123.0, -1.0)