gpt4 book ai didi

c++ - 为什么 const 模板化引用类型不同于 const 引用类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:59 25 4
gpt4 key购买 nike

考虑这个模板:

template< typename T, typename RefT = T& >
class foo
{
typedef const RefT const_ref_t;
typedef const T& another_const_ref_t;

//...

};

我假设类型 const_ref_tanother_const_ref_t将是等效的。两者都是 const T&的。但他们不是。唉,下面对它们不等价的证明是相当详尽的。它取决于使用 dynamic_cast<>检查另一个类的类型。

class abstractBase
{
public: virtual ~abstractBase() {}
};

template< typename T >
class otherClass : public abstractBase
{
};

template< typename T, typename RefT = T& >
class foo
{
typedef const RefT const_ref_t;
typedef const T& another_const_ref_t;

public:
void discover( abstractBase* p )
{
otherClass< const_ref_t >* a =
dynamic_cast< otherClass< const_ref_t >* >( p );
otherClass< another_const_ref_t >* b =
dynamic_cast< otherClass< another_const_ref_t >* >( p );

assert( a ); // Fails
assert( b ); // Succeeds
}
};

void fn()
{
abstractBase* p = new otherClass< const int& >();
foo< int > f;
f.discover( p ); // Assertion on 'a' fails.
}

抱歉,这太复杂了,但这是我发现问题的情况的简化版本。

那么问题来了。此代码处理 const int& , foo< int >::const_ref_t , 和 foo< int >::another_const_ref_t作为等价物,考虑到 typedef,这似乎是合理的。然而dynamic_cast<>只对待 foo< int >::another_const_ref_t相当于const int& .在另一种 ( foo< int >::const_ref_t ) 情况下,它将返回 null。

为什么?

最佳答案

考虑一下:

typedef Foo T;
typedef T & TRef;
typedef T const & TCRef;

现在 TRefFoo & 相同,TCRefconst Foo & 相同。

但是,const TRef 等同于const (TRef) = const (Foo &),而不是(const Foo)&。但引用类型始终是常量,因此额外的 const 不会添加任何内容。

如果您更喜欢与指针进行比较:T& 本质上类似于 T * const,因此 TRef const 类似于 (T * const) const,它只是折叠成 T * const

关于c++ - 为什么 const 模板化引用类型不同于 const 引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8369760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com