在我尝试学习 Rust 的过程中,我从一些基本练习开始。我写了一个简单的函数,我希望它是惯用的 rust 来计算整数中设置位的数量。
fn bit_count(x: u32) -> u32 {
(0..32).into_iter().map(|i| (x >> i) & 1).sum()
}
fn main() {
println!("{} has {} set bits.", 5, bit_count(5));
}
Run Code Online (Sandbox Code Playgroud)
现在我想让函数通用,以便我可以传递任何整数类型:i32, u32, i64, u64... 等。
我对 C++ 中的 tmp 非常熟悉,但是我对 rust 泛型的尝试失败了,到目前为止我有这个:
extern crate num;
fn bit_count<T>(x: T) -> T
where
T: num::Integer + std::ops::BitAnd + std::ops::Shr + num::NumCast,
std::ops::Range<T>: std::iter::IntoIterator,
{
(T::zero()..num::NumCast::from(32).unwrap())
.into_iter()
.map(|i| (x >> num::NumCast::from(i)) & T::one())
.sum()
}
fn main() {
println!("{} …Run Code Online (Sandbox Code Playgroud) 我读过这篇文章关于使用placement new来重置a boost::shared_ptr同时避免额外的内存分配,并假设可以为a做同样的,如果不相似的话std::unique_ptr?我的问题是当std::unique_ptr类型是什么时Base*可以指向任何类型,如果类的大小不同,那么工作是否Derived*会placement new按预期Derived进行?这样的事情可能是:
class Base
{
public:
Base() {}
virtual ~Base(){}
};
class Foo : public Base
{
public:
Foo() : Base() {}
virtual ~Foo(){}
int a;
int b;
};
class Bar : public Base
{
public:
Bar() : Base() {}
virtual ~Bar() {}
int a;
};
int main()
{
std::unique_ptr<Base> bp(new Bar());
bp->~Base(); //edit: call destructor
void* rawP = dynamic_cast<void*>(bp.release());//edit: cast to void* …Run Code Online (Sandbox Code Playgroud) 在编译我的项目时,我得到警告匿名联合中声明的匿名类型是扩展名[-Wnested-anon-types].我的代码包含这个联合:
union
{
uint32_t m_bits; // All bits
struct
{
uint32_t significand : 23;
uint32_t exponent : 8;
uint32_t sign : 1;
} IEEE;
};
Run Code Online (Sandbox Code Playgroud)
至于网站上的其他答案已经说过,如果我IEEE从结构中省略了名称,我只会期望这个警告.但目前结构不应该是匿名类型?
比如说我有两个简单的功能:
void a(int x)
{
//do something with x
}
void b(int x, float y)
{
// do something with x and y
}
Run Code Online (Sandbox Code Playgroud)
我希望有一个具有可变数量的args的单个函数,它可以根据标志调用上述两个:
template<typename... Args>
void varArgs(bool a_or_b, Args... args)
{
if (a_or_b)
a(args...);
else
b(args...);
}
Run Code Online (Sandbox Code Playgroud)
该标志将告诉我们是否要使用第一个或第二个函数,但是因为模板在编译时被实例化,所以这将不起作用.我读过constexpr if但是我只能使用c ++ 14所以我想知道是否有其他选择?
编辑:bool可以是编译时常量,而不是运行时参数.