如何使用可变参数模板构建开关盒
How to build switch-case with variadic templates
我想构建函数,如下所示:
template< int ... values>
constexpr bool check( int i ) noexcept
{
switch(i)
{
case values[0]: case values[1]: ... case values[n-1] : // only illustrated.
return true;
default: return false;
}
}
我可以制作该功能吗?
更新:谢谢,现在我知道如何实现:
template< int ... values> struct checker;
template< int head, int ... tail> struct checker<head, tail...>
{
static constexpr bool apply( int i ) noexcept {
return i == head || checker<tail...>::apply(i);
}
};
template<> struct checker<>
{
static constexpr bool apply( int ) noexcept { return false; }
};
template< int ... values >
constexpr bool check(int i) noexcept { return checker<values...>::apply(i); }
UPDATE2:我不知道,好不好,但我找到了这个解决方案:
template<size_t N>
constexpr bool any_of( bool( && array)[N], size_t index = 0) noexcept
{
return (index == N ) ? false
: ( array[index] || any_of( std::forward< decltype(array)>(array), 1+index) );
}
template< int ... values >
constexpr bool check(int i) noexcept
{
using list = bool[sizeof...(values)];
return any_of( list{ ( i == values) ... } );
}
template<>
constexpr bool check <>(int i) noexcept { return false; }
我认为不可能以任何方式使用switch
语法。但这应该有效:
template < int head, int ... values >
struct checker
{
static constexpr bool value(int i) noexcept
{ return i == head || checker<values...>::value(i); }
};
template < int head >
struct checker<head>
{
static constexpr bool value(int i) noexcept
{ return i == head; }
};
template< int ... values>
constexpr bool check( int i ) noexcept
{
return checker<values...>::value(i);
}
现场示例
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 无法在 CLion 中构建 C++ 项目
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用ndk-build.cmd构建Android.so文件
- 既然存在危险,为什么项目要使用-I include开关
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 为什么这个音频包络不能通过开关的情况?
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 构建一个由C和C++文件组成的库
- 有人知道为什么在开关中使用stoi函数会返回恒定的错误吗
- llvm构建器向基本块添加终止符
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 如何跨平台将二进制资源构建到程序中?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- C 和 C++ 中开关语句的案例标签的常量值,但显示不同的行为
- 如何解决 Ninja c++ 构建和执行问题
- 如何使用可变参数模板构建开关盒