【发布时间】:2020-11-05 02:47:18
【问题描述】:
我对以下代码感到困惑,其中Baz 类通过代理类Bar 提供对其内部数据的访问权限:
struct Foo{};
template<class T>
struct Bar
{
Bar(T &val_): val(val_) {}
T &val;
};
struct Baz
{
Bar<const Foo> get() const {return Bar<const Foo>(foo);}
Bar<Foo> get() {return Bar<Foo> (foo);}
Foo foo;
};
struct FooBaz
{
FooBaz(Baz &baz_): baz(baz_) {}
// Bar<const Foo> get() const {return baz.get();} // this do not compile
Bar<const Foo> get() const {return const_cast<const Baz &>(baz).get();} // the const_cast seems to be required
Baz &baz;
};
看来我必须做一个const_cast 才能调度到正确的Baz::get() 函数。
我不明白的第一件事是,如果 FooBaz::baz 是普通的 Baz 而不是参考,它会起作用:
struct Foo{};
template<class T>
struct Bar
{
Bar(T &val_): val(val_) {}
T &val;
};
struct Baz
{
Bar<const Foo> get() const {return Bar<const Foo>(foo);}
Bar<Foo> get() {return Bar<Foo> (foo);}
Foo foo;
};
struct FooBaz
{
FooBaz(Baz &baz_): baz(baz_) {}
Bar<const Foo> get() const {return baz.get();} // Ok
Baz baz;
};
我对 const 函数成员的理解是,它使 this 指向 const 的指针,但实际上我并不完全清楚它的含义......所有数据成员都'好像他们是常量'?有明确的参考吗?
另一个有趣的事情是,如果我使用 std::reference_wrapper 作为代理类,那么它可以在没有 const_cast 的情况下工作:
#include <functional>
struct Foo {};
struct Baz
{
std::reference_wrapper<const Foo> get() const {return std::cref(foo);}
std::reference_wrapper<Foo> get() {return std::ref (foo);}
Foo foo;
};
struct FooBaz
{
FooBaz(Baz &baz_): baz(baz_) {}
std::reference_wrapper<const Foo> get() const {return baz.get();} // Ok
Baz &baz;
};
std::reference_wrapper 有什么魔力?
谢谢!
【问题讨论】:
标签: c++ templates const-correctness