为什么const模板化引用类型不同于const引用类型?
Why is a const templated reference type different from a const reference type?
考虑这个模板:
template< typename T, typename RefT = T& >
class foo
{
typedef const RefT const_ref_t;
typedef const T& another_const_ref_t;
//...
};
我假设类型const_ref_t
和another_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
视为等效的,在给定类型的情况下,这似乎是合理的。然而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;
现在TRef
与Foo &
相同,TCRef
与const Foo &
相同。
但是,const TRef
与const (TRef) = const (Foo &)
相同,而不是(const Foo)&
。但是引用类型总是常量,所以额外的const
不会增加任何东西。
如果你喜欢与指针进行比较:T&
本质上像T * const
,所以TRef const
就像(T * const) const
,它只是折叠成T * const
。
相关文章:
- 强制转换为引用类型
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 视觉工作室 2017;启用 /permissive 时,类型 "const wchar_t *" 的参数与类型 "PWSTR" 的参数不兼容
- 自定义引用类型
- Java 中是否有类似于 C++ 中引用类型"&"的内容?
- 错误:对类型 'const ItemInstance' 的引用无法绑定到类型 'void' 的右值
- 为什么"const auto [x, y]"绑定到引用类型时没有按预期运行?
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- C++:从类型"int*"的表达式初始化类型"const int*&"的引用无效
- 错误:从类型"testGetter* const"的表达式初始化类型"const testGetter*&"的引用无效
- 尝试使用 uint*& 作为常量单元*&失败:从类型"uint8_t"的表达式初始化类型"const uint8_t*&"的引用无效
- 错误:从类型"const int"的表达式初始化类型"int"的引用无效
- find_if错误:从类型为"node*"的表达式初始化类型"const node&"的引用无效
- 为什么当 T 是引用类型时,const T& 参数中的 const 会消失?
- 为什么模板不隐式实例化为const或引用类型?
- 为什么const模板化引用类型不同于const引用类型?
- Clang:将引用绑定到类型 'const TClass' 的值会删除限定符
- 如何复制(或交换)包含引用或const成员的类型的对象
- 从类型 'const char*&' 的右值初始化 'const char *' 类型的非常量引用无效
- 引用(类型 &)"non-const lvalue reference to type cannot bind"错误,但指针(类型 *)不错误