如果A类修改其构造参数,我可以用const参数初始化const A吗? [英] If class A modifies its construction parameters, can I initialize const A's with const parameters?

查看:253
本文介绍了如果A类修改其构造参数,我可以用const参数初始化const A吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

class A final { 
    int& ir; 
public:
    A(int& x) : ir(x) { }
    void set(int y) { ir = y; } // non-const method!
    int get() const { return ir; }
};

const int i;

显然我不能拥有

 A a(i);

因为这会打破常数。但我也不能有

since that would breaks constness. But I also cannot have

 const A a(i);

尽管事实上这不会破坏常量。 C ++不支持const-onlyctors,例如。在这种情况下需要一个 const int& 。是否有办法获得 const A a 包装对 i 的引用 - 除了

despite the fact that this will not break constness de-facto. C++ doesn't support "const-only" ctors, e.g. in this case one which would take a const int&. Is there a way to get const A a wrapping a reference to i - other than

A a(const_cast<int &>(i))

推荐答案

Const意味着对象在构造函数结束和析构函数开始(在构建期间,你必须能够改变对象)。 C ++没有对于const对象优选的排序的准备构造函数。

"Const" means that the object is constant during between the constructor end and destructor begin (during construction, you must be able to change the object). C++ doesn't have a "preparation constructor" of sorts that is preferred for const objects.

您可以通过应用 boost :: variant 来尝试此解决方法。这在编译时不是完全类型安全的,但在运行时通过至少抛出异常来检测错误。

You can try this workaround by applying boost::variant. This is not completely type-safe at compile time, but detect errors at runtime by throwing an exception at least.

#include <boost/variant.hpp>
#include <iostream>

class R {
  boost::variant<int&, const int&> v;
public:
  R(int&v):v(v) { }
  R(const int&v):v(v) { }

  // works with both
  int get() const { 
     return boost::apply_visitor( 
        [](int x){return x;}, v); 
  }

  // only works for non-const A. If at construction, a const
  // int was passed, throws an error at runtime
  void set(int x) {
     boost::get<int&>(v) = x;
  }
};


int main() {
  int a = 0;
  const int b = a;
  R r1(a);
  R r2(b);
  const R r3(a);
  std::cout << r1.get() << r2.get() << r3.get();
  // r3.set(1); // compile error
  r1.set(1); // works
  r2.set(1); // runtime error
}

这篇关于如果A类修改其构造参数,我可以用const参数初始化const A吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆