【发布时间】:2020-12-04 15:53:33
【问题描述】:
带有 -fms-extensions 的 clang (this->ClassName::ClassName()) 支持显式构造函数调用 谢谢!
template<int k>
class Base {
public:
int num = 0;
Base(int sdsd):num(sdsd) {}
void func(int v) {num = 12 + v;}
};
template <int Ty>
void callA(Base<Ty> *obj){
(reinterpret_cast< Base<Ty>*>(obj))->Base::Base(1); // error: cannot refer to type member 'Base' in 'Base<99>' with '->'
// but with MS compiler in windows that's right
(reinterpret_cast< Base<Ty>*>(obj))->Base::func(1); // ok
}
void callB(void *obj){
(reinterpret_cast< Base<100>*>(obj))->Base::Base(2);// ok
(reinterpret_cast< Base<100>*>(obj))->Base::func(1); // ok
}
int main(int argn, char** argc) {
Base<99> a(0);
callA(&a);
callB(&a);
}
【问题讨论】:
-
这是什么?调用
reinterpret_cast转换为完全不同的模板实例对我来说听起来像是未定义的行为。尝试直接调用构造函数的目的是什么?您是否在尝试模拟 placement-new? -
When to use reinterpret_castreinterpret_cast
(v)是强制转换,比如(type)v,但是这种转换经常报错 -
事实上,(reinterpret_cast
*>(obj))。 ((Base ) (void*) obj) -
两个完全不相关的类模板实例是不可转换的。我认为这里的行为是未定义的或特定于实现的。我知道
reinterpret_cast做了什么,它不只是为了解决由于您尝试一些根本性危险的事情而导致的根本性错误。 -
不是。
obj->Base::Base(1);还是错误,reinterpret_cast不是重点
标签: c++