integral_constant 的编译时布尔运算?
Compile-time boolean operations for an integral_constant?
在 C++ 标准库中,是否存在对 integral_constant<bool, X>
进行布尔运算的模板类型(其中 X
是 true
或 false
)?
作为一个简单的例子,您有两个这样的函数重载:
void foo_impl(false_type){
cout << "false" <<endl;
}
void foo_impl(true_type){
cout << "true" <<endl;
}
这些函数中的一个由另一个函数根据恒定条件选择:
struct first_tag{};
struct second_tag{};
struct third_tag{};
template <typename TTag>
void foo(TTag role){
foo_impl(typename constant_or<typename is_same<role, first_tag>::type, typename is_same<role, second_tag>::type>::type{});
}
在这种情况下,如果 foo()
的参数是 first_tag
或 second_tag
类型,则将调用 foo_impl()
的 true
版本, 因此使用假设类型 constant_or
.
虽然编写我自己的 constant_or
版本很简单,但 C++ 标准库中是否已经存在这样的类型?
叫做std::conditional
。类似的元函数、合取、析取、取反也将出现在 C++17 中。
首先让我们更正您的错字
template <typename TTag>
void foo(TTag){
foo_impl(typename constant_or<typename is_same<TTag, first_tag>::type, typename is_same<TTag, second_tag>::type>::type{});
}
is_same
作用于 类型 而不是值。
然后让我们指出您可以只使用 is_same
中的值。
template <typename TTag>
void foo(TTag){
foo_impl(integral_constant<bool, is_same_v<TTag, first_tag> | is_same_v<TTag, second_tag>>{});
}
大功告成。也节省了很多打字,这总是一个加号。
关于节省打字的注意事项(因为上帝禁止)
template<bool B>
using bool_constant = integral_constant<bool, B>;
由标准定义。
在 C++ 标准库中,是否存在对 integral_constant<bool, X>
进行布尔运算的模板类型(其中 X
是 true
或 false
)?
作为一个简单的例子,您有两个这样的函数重载:
void foo_impl(false_type){
cout << "false" <<endl;
}
void foo_impl(true_type){
cout << "true" <<endl;
}
这些函数中的一个由另一个函数根据恒定条件选择:
struct first_tag{};
struct second_tag{};
struct third_tag{};
template <typename TTag>
void foo(TTag role){
foo_impl(typename constant_or<typename is_same<role, first_tag>::type, typename is_same<role, second_tag>::type>::type{});
}
在这种情况下,如果 foo()
的参数是 first_tag
或 second_tag
类型,则将调用 foo_impl()
的 true
版本, 因此使用假设类型 constant_or
.
虽然编写我自己的 constant_or
版本很简单,但 C++ 标准库中是否已经存在这样的类型?
叫做std::conditional
。类似的元函数、合取、析取、取反也将出现在 C++17 中。
首先让我们更正您的错字
template <typename TTag>
void foo(TTag){
foo_impl(typename constant_or<typename is_same<TTag, first_tag>::type, typename is_same<TTag, second_tag>::type>::type{});
}
is_same
作用于 类型 而不是值。
然后让我们指出您可以只使用 is_same
中的值。
template <typename TTag>
void foo(TTag){
foo_impl(integral_constant<bool, is_same_v<TTag, first_tag> | is_same_v<TTag, second_tag>>{});
}
大功告成。也节省了很多打字,这总是一个加号。
关于节省打字的注意事项(因为上帝禁止)
template<bool B>
using bool_constant = integral_constant<bool, B>;
由标准定义。