如何检查模板参数是否为2的幂? [英] How do I check if a template parameter is a power of two?

查看:58
本文介绍了如何检查模板参数是否为2的幂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个静态分配 2 ^ N字节数组的结构,但是我不希望这种结构的用户将这个大小指定为指数。示例:

  my_stupid_array< char,32> a1; // 我要这个! 
my_stupid_array< char,5> a2; //不是这个...

如何检查此模板参数是否为2的幂 and 向用户发出有关此消息的好消息吗?



我已经可以通过一个简单的模板进行检查了:

  template< int N> 
struct is_power_of_two {
枚举{val =(N> = 1)& !(N&(N-1))};
};

但是,我无法通过理性的消息警告用户。有想法吗?



编辑



修复了模棱两可的示例。



编辑



1确实是2的幂。修正了! :)



编辑



使用BOOST_STATIC_ASSERT,我收到了此编译错误对于带有GCC的代码:

  template< int N> 
struct is_power_of_two {
枚举{val =(N> = 1)& !(N&(N-1))};
BOOST_STATIC_ASSERT(val);
};

错误

  .. \main.cpp:29:1:错误:对不完整类型'boost :: STATIC_ASSERTION_FAILURE< false>'


http://ideone.com/cMfEf



编辑



哦,我明白了。那就是断言失败时我应该得到的消息。但这不能给用户一些理智的消息。 :(

解决方案

这几天,有了 constexpr 有点扯动黑客您可以

  constexpr bool is_powerof2(int v){
return v&&((v&(v-1))== 0);
}


I want to create a structure that allocates statically an array of 2^N bytes, but I don't want the users of this structure to specify this size as the exponent. Example:

my_stupid_array<char, 32> a1; // I want this!
my_stupid_array<char, 5> a2; // And not this...

How do I check if this template parameter is a power of two and warn the user with a nice message about this?

I've been able to check for this with a simple template:

template<int N>
struct is_power_of_two {
    enum {val = (N >= 1) & !(N & (N - 1))};
};

However, I'm unable to warn the user about this with a sane message. Any ideas?

EDIT

Fixed the ambiguous example.

EDIT

1 is a power of two indeed. Fixed that! :)

EDIT

Using BOOST_STATIC_ASSERT, I'm getting this compile error for this code with GCC:

template<int N>
struct is_power_of_two {
    enum {val = (N >= 1) & !(N & (N - 1))};
    BOOST_STATIC_ASSERT(val);
};

Error

..\main.cpp:29:1: error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>' 

http://ideone.com/cMfEf

EDIT

Oh, I get it. That was the message that I'm supposed to get when the assert fails. But that fails to give the user some sane message. :(

解决方案

These days, with constexpr and the bit twiddling hacks you can just

constexpr bool is_powerof2(int v) {
    return v && ((v & (v - 1)) == 0);
}

这篇关于如何检查模板参数是否为2的幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆