iva*_*rec 16 c++ templates static-assert constexpr c++11
我想创建一个静态分配2 ^ N字节数组的结构,但我不希望此结构的用户将此大小指定为指数.例:
my_stupid_array<char, 32> a1; // I want this!
my_stupid_array<char, 5> a2; // And not this...
Run Code Online (Sandbox Code Playgroud)
如何检查此模板参数是否为2的幂并警告用户有关于此的好消息?
我已经能够通过一个简单的模板检查这个:
template<int N>
struct is_power_of_two {
enum {val = (N >= 1) & !(N & (N - 1))};
};
Run Code Online (Sandbox Code Playgroud)
但是,我无法通过合理的消息警告用户.有任何想法吗?
编辑
修复了模棱两可的例子.
编辑
1确实是2的幂.修好了!:)
编辑
使用BOOST_STATIC_ASSERT,我收到此代码与GCC的编译错误:
template<int N>
struct is_power_of_two {
enum {val = (N >= 1) & !(N & (N - 1))};
BOOST_STATIC_ASSERT(val);
};
Run Code Online (Sandbox Code Playgroud)
错误
..\main.cpp:29:1: error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>'
Run Code Online (Sandbox Code Playgroud)
编辑
哦,我明白了.这是断言失败时我应该得到的消息.但这无法给用户一些明智的信息.:(
Tem*_*Rex 22
static_assert to rescue(仅限C++ 11,取消注释BOOST_STATIC_ASSERT for C++ 03):
#include<iostream>
// #include <boost/static_assert.hpp>
template<int N>
struct is_power_of_two {
enum {val = N && !(N & (N - 1))};
static_assert(val, "should use a power of 2 as template parameter");
// BOOST_STATIC_ASSERT(val); // without C++11 support, won't take a string message
};
int main()
{
std::cout << is_power_of_two<2>::val << "\n";
std::cout << is_power_of_two<3>::val << "\n";
}
Run Code Online (Sandbox Code Playgroud)
UPDATE1:其他想法(我知道你不想要这个,但对大型指数来说要容易得多):
template<int N>
make_power_of_two
{
enum { val = 1 << N };
};
my_stupid_array<char, make_power_of_two<5>::val > a1; // size 2^5 = 32
Run Code Online (Sandbox Code Playgroud)
UPDATE2:基于@sehe在聊天中的评论,您也可以为constexpr功能执行此操作
constexpr bool is_power_of_two(int x)
{
return x && ((x & (x-1)) == 0);
}
Run Code Online (Sandbox Code Playgroud)
seh*_*ehe 18
这些天来,你可以随便constexpr和笨拙的骇人听闻
constexpr bool is_powerof2(int v) {
return v && ((v & (v - 1)) == 0);
}
Run Code Online (Sandbox Code Playgroud)
Set*_*gie 11
您可以使用static_assert提供错误消息:
template<int N>
struct is_power_of_two {
static_assert((N > 1) & !(N & (N - 1)), "Template parameter must be a power of two.");
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4170 次 |
| 最近记录: |