gpt4 book ai didi

c++ - 确定可变模板参数是编译时间

转载 作者:行者123 更新时间:2023-12-05 01:49:11 26 4
gpt4 key购买 nike

假设我想定义一个依赖于某些类型的类型:

    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
>;

是否有一种简洁的方法来确定传递给采用可变参数的模板的参数?

最佳答案

基本上,您想要附加可选列表。为此,您首先需要添加列表:

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>;

关于c++ - 确定可变模板参数是编译时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74392924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com