我正在使用另一個人代碼,使用功能 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);
儘管演員陣容從未製作過?根據這個推理也'如果(1 == 0){語法錯誤; ''應該編譯。包含轉換的代碼被實例化,所以它必須是有效的。我不熟悉C++ 11和超越模板的東西,但也許一個constexpr如果可以幫助 – user463035818
'如果constexpr(..)'在C++ 17中。 – Jarod42