2017-10-19 104 views
1

我正在使用另一個人代碼,使用功能 doSomething取決於兩個模板:stageT。 我知道,他們可以採取我現在需要投DerivedTwoBaseTwoDerivedOneBaseOne狀態(MicroDerivedOne)或(MacroDerivedTwo編譯錯誤模板上的非調用功能

doSomething。如代碼中所示,當舞臺合適時,轉換僅爲 ,即它們總是o.k. 我仍然得到編譯錯誤,因爲即使這種轉換從不做出,也不可能將DerivedOne 轉換爲BaseTwo

問題: 如何在不改變相關類和模板的一般結構的情況下編譯此代碼? (這會打破許多其他代碼部分)。 最好我只想更改doSomething

演員陣容發生b.c.我需要調用一個重載函數,它可以是 需要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); 
+0

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

+0

'如果constexpr(..)'在C++ 17中。 – Jarod42

回答

1

你可以使用:

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

現在爲什麼會這樣派上用場?

因爲現在if語句包含constexpr,它將在編譯時間處評估其條件,並且只有在條件計算結果爲true時纔會編譯它的主體。這意味着該機構可能是格式不正確,但代碼能夠編譯。閱讀更多here