Wou*_*jen 5 c++ templates variadic-templates c++-concepts
我想写模板来构造让我们说一个输入端口.这可以从单个输入输出端口或输入引脚列表中完成.我更喜欢这些模板具有相同的名称.我有输入输出端口和输入引脚的概念.我可以写
template< typename... arguments >
struct port_in ....
template< pin_in T >
struct port_in<> ....
Run Code Online (Sandbox Code Playgroud)
但现在列表版本将接受任何类型.我可以在实现中检查它,但这会降低用户在传递不适合的类型时获得的错误消息.我可以以某种方式将列表限制为一种类型,但允许另一种类型的单个模板参数吗?
如果您想确保用户始终收到合理的错误消息,那么您需要约束基本模板。假设您现有的概念被命名为InputPin和InputOutputPort,您可以限制基本模板以接受一系列输入引脚或单个输入/输出端口,如下所示:
template<class... Ts>
concept bool AllInputPins = (InputPin<Ts> && ...);
template<class... Ts>
concept bool OneInputOutputPort = sizeof...(Ts) == 1 && (InputOutputPort<Ts> && ...);
template <class... Args>
requires AllInputPins<Args...> || OneInputOutputPort<Args...>
struct port_in {
// ...
};
Run Code Online (Sandbox Code Playgroud)