相关疑难解决方法(0)

三元运算符隐式转换为基类

考虑一下这段代码:

struct Base
{
    int x;
};

struct Bar : Base
{
    int y;
};

struct Foo : Base
{
    int z;
};

Bar* bar = new Bar;
Foo* foo = new Foo;

Base* returnBase()
{
    Base* obj = !bar ? foo : bar;
    return obj;
}

int main() {
    returnBase();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这在Clang或GCC下不起作用,给我:

错误:不同指针类型'Foo*'和'Bar*'之间的条件表达式缺少一个强制转换Base*obj =!bar?foo:bar;

这意味着要编译我必须将代码更改为:

Base* obj = !bar ? static_cast<Base*>(foo) : bar;
Run Code Online (Sandbox Code Playgroud)

由于隐式转换为Base*存在,是什么阻止编译器这样做?

换句话说,为什么没有Base* obj = foo;演员而是使用?:操作员的工作呢?是因为我不清楚我想使用这Base部分吗?

c++ ternary-operator language-lawyer implicit-conversion c++17

48
推荐指数
3
解决办法
2530
查看次数

获取类层次结构中类型的基类

是否可以在类层次结构中获取基类类型?

例如:

struct A{};
struct B{} : public A;
struct C{} : public B;
Run Code Online (Sandbox Code Playgroud)

我想要一些typedef Base<T>::Type内部像这样的模板:

Base<A>::Type == A
Base<B>::Type == A
Base<C>::Type == A
Run Code Online (Sandbox Code Playgroud)

这可能吗?我有多重继承的情况怎么样?

c++ c++11

13
推荐指数
3
解决办法
9602
查看次数