c语言case无参,如何使用可变参数模板构建switch-case
我想構(gòu)建函數(shù),如:
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;
}
}
我能做那個(gè)功能嗎?
更新:謝謝,現(xiàn)在我知道如何實(shí)現(xiàn):
template< int ... values> struct checker;
template< int head, int ... tail> struct checker
{
static constexpr bool apply( int i ) noexcept {
return i == head || checker::apply(i);
}
};
template<> struct checker<>
{
static constexpr bool apply( int ) noexcept { return false; }
};
template< int ... values >
constexpr bool check(int i) noexcept { return checker::apply(i); }
更新2:我不知道,這是好還是不行,但我找到了這個(gè)解決方案:
template
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; }
總結(jié)
以上是生活随笔為你收集整理的c语言case无参,如何使用可变参数模板构建switch-case的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 新兵丕授衔前申请退回有军籍吗新兵在授衔前
- 下一篇: 谷歌新语言重写android,谷歌将推新