Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板中未调用强制转换函数的编译错误_C++_Templates_If Statement_Inheritance_Casting - Fatal编程技术网

C++ 模板中未调用强制转换函数的编译错误

C++ 模板中未调用强制转换函数的编译错误,c++,templates,if-statement,inheritance,casting,C++,Templates,If Statement,Inheritance,Casting,我正在使用另一个使用函数的persons代码 doSomething这取决于两个模板:stage和T。 我知道他们可以拿州(Micro, DerivedOne)或(Macro,DerivedOne) 在doSomething中,我现在需要将derivedtower转换为BaseTwo和derivedtowne转换为BaseOne。如代码中所示,转换仅限于 在舞台合适的时候制作,也就是说,它们总是好的。 我仍然会遇到编译错误,因为无法强制转换DerivedOne 到BaseTwo,即使从未进行此转

我正在使用另一个使用函数的persons代码
doSomething
这取决于两个模板:
stage
T
。 我知道他们可以拿州(
Micro
DerivedOne
)或(
Macro
DerivedOne

doSomething
中,我现在需要将
derivedtower
转换为
BaseTwo
derivedtowne
转换为
BaseOne
。如代码中所示,转换仅限于 在舞台合适的时候制作,也就是说,它们总是好的。 我仍然会遇到编译错误,因为无法强制转换
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);

};
enum阶段{
微型的,
宏
};
一级
{
INTA;
};
二班
{
int b;
};
派生类:公共BaseOne
{
INTC;
};
派生类二:公有基二,公有基一
{
int d;
};
模板
阶级实践者{
模板
无效剂量测定(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);
#包括“aTest.h”
模板<阶段>
模板
无效行为人::剂量(T){
//根据舞台的不同,我们需要将t投到一垒或二垒
如果(阶段==微)
{
重载函数((BaseOne)t);
}
if(stage==宏)
{
重载函数((BaseTwo)t);
}
}
模板类执行器;
模板类执行器;
模板无效行为人::doSomething(DerivedOne t);
模板无效行为人::doSomething(派生两个t);
您可以使用:

if constexpr (stage == Macro)
     overloadedFunction( (BaseTwo) t );
为什么这会派上用场


因为现在if语句包含
constexpr
,它将在编译时计算其条件,并且仅当条件的计算结果为true时才编译其主体。这意味着主体可能格式不正确,但代码可能无法编译。阅读更多信息。

即使演员从未出演过?根据这个推理,如果(1==0){syntax error;}也应该编译。包含强制转换的代码是实例化的,因此它必须是有效的。我对c++11及模板以外的内容不太熟悉,但在c++17中,如果使用constexpr(…),可能需要一个constexpr if。