小编Dan*_*n R的帖子

为什么必须冗余指定指针特征边界?

考虑以下情况,有两个Traits。第一个Trait用于指针类型,第二个Trait用于常规对象。第二个特征有一个HRTB,因此任何对实现第二个特征的类型的引用都必须实现第一个特征:

pub trait PtrTrait {}

pub trait RegTrait
where
    for<'a> &'a Self: PtrTrait,
{
}
Run Code Online (Sandbox Code Playgroud)

是的,这确实有效!在下文中,如果impl不包含第一个泛型,编译器会抱怨:

pub struct S();

// Note, this impl IS needed for the next impl to compile.
impl<'a> PtrTrait for &'a S {}

impl RegTrait for S {}
Run Code Online (Sandbox Code Playgroud)

问题是编译器在编写泛型函数时似乎没有记住这一点。以下函数定义无法编译:

pub fn bar<T: RegTrait>() {}
Run Code Online (Sandbox Code Playgroud)

错误来自rustc简单地说,for<'a> &'a T: PtrTrait该类型不满足trait bound &'a T。如果我where在函数中添加一个子句:

where for<'a> &'a T: PtrTrait
Run Code Online (Sandbox Code Playgroud)

那么它就起作用了——但是如果它已经是对特征本身的一个约束,为什么还需要它呢?

操场

rust

5
推荐指数
0
解决办法
81
查看次数

多拷贝构造函数继承中令人惊讶的行为

从C++ 11开始,可以有两个复制构造函数,一个采用类型参数,另一个采用类型T&参数const T&.

我有一种情况,即(似乎)添加第二个复制构造函数会导致在构造函数在派生类中继承时不会调用任何一个.当两者都存在时,复制构造函数被模板化构造函数覆盖.

这是一个MWE:

struct A {
  template <typename... Args>
  A (Args&&... args)
  { std::cout << "non-default ctor called\n"; }

  A (A&) { std::cout << "copy ctor from non-const ref\n"; }
};

struct C :public A { using A::A; };

int main() {
  C c1;
  C c2(c1);
}
Run Code Online (Sandbox Code Playgroud)

运行此代码,我们看到输出

non-default ctor called
copy ctor from non-const ref
Run Code Online (Sandbox Code Playgroud)

这是预期的.

但是,添加一个额外的构造函数struct A如下:

  A (const A&) { }
Run Code Online (Sandbox Code Playgroud)

以某种方式导致其他复制构造函数不被调用,因此输出变为

non-default ctor called …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance constructor using-declaration c++11

3
推荐指数
1
解决办法
141
查看次数

设置 nullglob 时不会取消关联数组

当我在 bash 中设置 nullglob 时:

shopt -s nullglob
Run Code Online (Sandbox Code Playgroud)

然后声明一个关联数组:

declare -A arr=( [x]=y )
Run Code Online (Sandbox Code Playgroud)

我无法取消设置数组中的特定键:

unset arr[x]
echo ${#arr[@]} # still 1
Run Code Online (Sandbox Code Playgroud)

但是,取消设置nullglob使此操作像我期望的那样工作:

shopt -u nullglob
unset arr[x]
echo ${#arr[@]} # now it's 0; x has been removed
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?我不明白 shell globbing 如何与这种情况相关。我已经在 bash 4.4.19 和 5.0.0 上测试过了。

bash quotes associative-array glob shopt

3
推荐指数
1
解决办法
178
查看次数