编译错误模板上的非调用功能
问题描述:
我正在使用另一个人代码,使用功能 doSomething
取决于两个模板:stage
和T
。 我知道,他们可以采取我现在需要投DerivedTwo
到BaseTwo
和DerivedOne
到BaseOne
状态(Micro
, DerivedOne
)或(Macro
,DerivedTwo
)编译错误模板上的非调用功能
在doSomething
。如代码中所示,当舞台合适时,转换仅为 ,即它们总是o.k. 我仍然得到编译错误,因为即使这种转换从不做出,也不可能将DerivedOne
转换为BaseTwo
。
问题: 如何在不改变相关类和模板的一般结构的情况下编译此代码? (这会打破许多其他代码部分)。 最好我只想更改doSomething
。
演员阵容发生b.c.我需要调用一个重载函数,它可以是 需要BaseOne
或BaseTwo
。因此,要通过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
,它将在编译时间处评估其条件,并且只有在条件计算结果为true时才会编译它的主体。这意味着该机构可能是格式不正确,但代码能够编译。阅读更多here。
尽管演员阵容从未制作过?根据这个推理也'如果(1 == 0){语法错误; ''应该编译。包含转换的代码被实例化,所以它必须是有效的。我不熟悉C++ 11和超越模板的东西,但也许一个constexpr如果可以帮助 – user463035818
'如果constexpr(..)'在C++ 17中。 – Jarod42