是否可以在c ++中强制传递依赖对象的constness

Dmi*_*y J 3 c++ dependency-injection const

这是我想要阻止的:

class Dep; //for "dependency"

class C {
  private: 
    const Dep& dep_; //or std::shared_ptr if I want to guarantee proper lifetime of dependency
  public:
    C(const Dep& dep) : dep_(dep){}
}

Dep d(Arg arg);
C obj(d); //obj can't change d
d.some_non_const_method(); //But it's creator can :(
Run Code Online (Sandbox Code Playgroud)

我想得到的是,创建C对象的唯一正确方法是这样的:

Dep d(Arg arg);
d.some_non_const_method();
const Dep d1(d); //or move constructor if appropriate
C obj(d1); //Object d1 must be const!
d1.some_non_const_method(); //compile error, so obj can be sure that the dependency he's got is really const.
Run Code Online (Sandbox Code Playgroud)

有没有办法通过语法强制执行此操作?

PS Dependency旨在共享,所以我不能std::unique_ptr在这里使用.

lll*_*lll 5

如果我正确理解你的问题,你只想接受一个const参数,并希望在const传递非参数时得到错误.

最简单的方法应该是将非const版本标记为delete:

class C {
  private:
    const Dep& dep_;
  public:
    C(const Dep& dep) : dep_(dep){}
    C(Dep &) = delete;
};
Run Code Online (Sandbox Code Playgroud)

然后:

Dep d;
C obj(d); // Error, deleted function selected

const Dep d1(d);
C obj(d1); // ok
Run Code Online (Sandbox Code Playgroud)