gpt4 book ai didi

c++ - 在未调用的转换函数上在模板中编译错误

转载 作者:行者123 更新时间:2023-11-30 05:08:28 25 4
gpt4 key购买 nike

我正在使用另一个使用函数的代码 doSomething 依赖于两个模板:stageT。我知道他们可以只采用状态 (Micro,DerivedOne) 或 (Macro, DerivedTwo)

doSomething 中,我现在需要将 DerivedTwo 转换为 BaseTwo 并将 DerivedOne 转换为 BaseOne。如代码中所示,转换仅在舞台合适的时候制作,即他们总是没问题。我仍然遇到编译错误,因为无法转换 DerivedOneBaseTwo,即使从未进行过此转换。

问题:如何在不更改所涉及类和模板的一般结构的情况下编译此代码? (这会破坏代码的许多其他部分)。最好我只想更改 doSomething

类型转换发生在公元前。我需要调用一个重载函数,它可以采用 BaseOneBaseTwo。因此,要传递 DerivedTwo,我需要显式转换它。

aTest.h

enum  Stage {
Micro,
Macro
};

class BaseOne
{
int a;
};

class BaseTwo
{
int b;
};


class DerivedOne : public BaseOne
{
int c;
};

class DerivedTwo: public BaseTwo, public BaseOne
{
int d;
};

template <Stage stage>
class Doer{
template <class T>
void doSomething( T t);

};

aTest.cpp

#include "aTest.h"

template< Stage stage >
template < class T >
void Doer<stage>::doSomething(T t) {


//depending on stage we need to cast t to BaseOne or BaseTwo
if( stage == Micro )
{
overloadedFunction( (BaseOne) t );
}
if( stage == Macro )
{
overloadedFunction( (BaseTwo) t );
}



}


template class Doer<Micro>;
template class Doer<Macro>;


template void Doer<Micro>::doSomething(DerivedOne t);
template void Doer<Macro>::doSomething(DerivedTwo t);

最佳答案

你可以使用:

if constexpr (stage == Macro)
overloadedFunction( (BaseTwo) t );

现在为什么它会派上用场?

因为现在 if 语句包含 constexpr,它将在编译时 评估其条件,并且仅当条件评估为真时才编译其主体。这意味着正文可能格式错误,但代码可以编译。阅读更多 here .

关于c++ - 在未调用的转换函数上在模板中编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46829957/

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