C ++可变参数模板AND和OR [英] C++ Variadic template AND and OR
问题描述
可以使用C ++ 11可变参数模板来完成 / * ??? * /
其中:
Can you use C++11 variadic templates to complete /* ??? */
in:
template<bool...v> struct var_and { static bool constexpr value = /* ??? */; };
,以便 var_and< v ...> :: value
在编译时通过布尔包 v
提供&
吗?
so that var_and<v...>::value
provides &&
over the boolean pack v
at compile-time?
对于 struct var_or< v ...>
对于 || ?
可以使用短路评估(在两种情况下)吗?
Can you use short-circuit evaluation (in both cases)?
修改:对接受的答案的更新中添加了C ++ 17 折叠表达式启用
Edit: An update to the accepted answer added that C++17 fold expressions enable
template<bool... v> constexpr bool var_and = (v && ...);
template<bool... v> constexpr bool var_or = (v || ...);
对于基于参数包的方法,似乎只有一种受限类型的短路评估 是可能的:在实例化 var_or< true,foo(),bar()>
时,仅调用 ||
一次,它也同时调用 foo
和 bar
。
It seems that, for parameter pack-based approaches, only a restricted type of "short-circuit evaluation" is possible: while instantiating var_or<true,foo(),bar()>
only calls ||
once, it also calls both foo
and bar
.
推荐答案
您不希望 value
成为typedef。
You don't want value
to be a typedef.
template<bool head, bool... tail>
struct var_and {
static constexpr bool value = head && var_and<tail...>::value;
};
template<bool b> struct var_and<b> {
static constexpr bool value = b;
};
显然,对于 || 。
短路评估并不重要,因为它只处理不会有任何副作用的常量表达式。
Short circuit evaluation doesn't matter because this only deals with constant expressions which won't have any side effects.
这是另一种方法,它会在发现错误值后立即停止递归生成类型,从而模拟一种短路:
Here's another method which stops recursively generating types as soon as it find a false value, emulating a kind of short circuiting:
template<bool head, bool... tail>
struct var_and { static constexpr bool value = false; };
template<bool... tail> struct var_and<true,tail...> {
static constexpr bool value = var_and<tail...>::value;
};
template<> struct var_and<true> {
static constexpr bool value = true;
};
C ++ 17的更新:使用折叠
Update for C++17: Using a fold expression makes this much simpler.
template<bool...v> struct var_and {
static constexpr bool value = (v && ...);
};
或者也使用enobayram建议的模板变量:
Or also using a template variable as enobayram suggests:
template<bool... b> constexpr bool var_and = (b && ...);
这篇关于C ++可变参数模板AND和OR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!