我正在對一些較舊/雜亂的代碼進行一些重構。我正在嘗試一點一點地改進。因為它適合專案,所以我開始在某個類上實作 CRTP(用于靜態多型性),我們稱之為sensor. 通過CRTP,現在有一個real和一個fake實作。
現在,我正在嘗試將模板放入interface_actions使用sensor. 我得出了這樣的結論:
class interface_actions
{
public:
template <class implementation>
interface_actions(sensor<implementation> detector)
: _detector(detector)
{}
// Lots of stuff that I don't want to touch
private:
#if (SOMETHING)
sensor<real> _detector;
#else
sensor<fake> _detector;
#endif
};
正如你所看到的,我不知道如何處理_detector而不必使整個類成為模板,所以我使用了前處理器......
_detector我想這更像是一個架構問題,但是如果不讓整個類成為模板,你將如何制作拍攝傳感器?在我看來,我必須從根本上重寫這部分代碼,但也許有更簡單的方法?
uj5u.com熱心網友回復:
你可以使用std::conditional_t:
class interface_actions
{
std::conditional_t<SOMETHING, sensor<real>, sensor<fake>> _detector;
};
如果SOMETHINGyield true,_detector將是 type sensor<real>,sensor<fake>否則。
但這僅在SOMETHING超出范圍時才有效 class interface_actions,否則您必須使該類采用模板。正如 pptaszni 建議的那樣,您可以創建一個默認模板引數來“隱藏”模板引數,這樣您的舊代碼interface_actions object;就不會受到影響:
template<bool is_real = true>
class interface_actions
{
std::conditional_t<is_real, sensor<real>, sensor<fake>> _detector;
};
int main() {
interface_actions foo;
static_assert(std::is_same_v<decltype(foo._detector), sensor<real>>);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508184.html
