【发布时间】:2020-05-11 18:04:06
【问题描述】:
所以我一直在阅读 Bjarne 的 Programming Principles and Practices in C++。基类/派生类的模板化对象的转换部分让我有点困惑。所以我尝试尝试不同的组合,偶然发现了一些奇怪的东西
#include <iostream>
class A {
public:
int i;
};
class B : public A {
int j;
};
template<typename T>
class Array_ref{
public:
Array_ref(T* pointer, int size) : p{pointer}, sz{size} {}
template<typename Q>
operator Array_ref<const Q>(){
static_cast<Q>(*static_cast<T*>(nullptr));
return Array_ref<const Q>{reinterpret_cast<Q*>(p), sz};
}
T& operator[](int n){
return p[n];
}
private:
T* p;
int sz;
};
void test_function(Array_ref<A* const> temp){
if(temp[0]->i)
std::cout<<"failed I guess"<<std::endl;
exit(0);
};
int main(){
B* testobj[1];
testobj[0] = new B;
testobj[0]->i = 0;
Array_ref<B*> a(testobj, 1);
test_function(a);
delete testobj[0];
exit(0);
}
void test_function(Array_ref<A* const> temp) 是困扰我的线路。因为如果我将它设为Array_ref<const A*>,它无法编译并出现无法从B* 转换为const A* 的错误,尽管据我所知,我已经提供了应该适合重载参数的转换规则。事实上,const A* 和 A* const 不是很不同吗?
如果有人能帮我解决我在哪里搞砸了,我会很高兴。非常感谢!
【问题讨论】:
-
static_cast<Q>(*static_cast<T*>(nullptr));怎么了?看起来像无条件的 UB。 -
temp[0]->i = 1;分配给一个常量
-
@QuentinUK 这是一个可取的行为,正如我所提到的,这更像是一个程序来清除我对常量关键字的疑虑,它只是一个剩余部分,我将编辑并删除它,所以它不会让任何人感到困惑
-
我的主要问题是关于
B*到const A*的转换 -
对于指针类型,“Ptr”,“const Ptr”表示指针是const而不是指向的东西。
标签: c++ templates c++14 overloading