假設我想定義一個依賴于某些型別的型別:
struct TimerPump{};
struct GuiPump{};
struct NetworkPump{};
template<class... Pumps>
class DispatcherT{};
using Dispatcher = DispatcherT< TimerPump, GuiPump, NetworkPump >;
我想讓 gui 和網路泵成為可選的。可能需要其中一個,或者兩者都需要,或者一個都不需要。我可以撰寫一個前處理器宏:
using Dispatcher = DispatcherT< TimerPump
#ifdef GUI_ENABLED
, GuiPump
#endif
#ifdef NETWORK_ENABLED
, NetworkPump
#endif
>;
但我正在尋找一種通過特征控制這些論點的方法
struct Traits
{
static constexpr bool gui = true;
static constexpr bool network = false;
};
using Dispatcher = DispatcherT< TimerPump
, Traits::gui ? GuiPump : null <--- need help here
, Traits::network ? NetworkPump : null
>;
有沒有一種簡潔的方法來確定傳遞給模板的引數,該模板采用可變引數?
uj5u.com熱心網友回復:
基本上,您希望附加可選串列。為此,您首先需要添加串列:
template<typename... Ts>
struct list {
template<typename T>
using append = list<Ts..., T>;
template<bool b, typename T>
using appendIf = std::conditional_t<b, list<Ts..., T>, list<Ts...>>;
template<template<class...> LT>
using applyTo = LT<Ts...>;
};
然后您可以從list<>(或您肯定擁有的任何型別)開始,然后在每個步驟中,使用::appendIf<condition, type>并以applyTo<DispatcherT>.
using Dispatcher =
list<TimerPump>
::appendIf<Traits::gui, GuiPump>
::appendIf<Traits::network, NetworkPump>
::applyTo<DispatcherT>;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531465.html
標籤:C 模板可变参数模板
