如何检查模板参数是否为2的幂?

时间:2012-05-14 14:35:39

标签: c++ templates c++11 constexpr static-assert

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

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

如何检查此模板参数是否为2的幂警告用户有关于此的好消息?

我已经能够通过一个简单的模板检查这个:

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

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

修改

修正了含糊不清的例子。

修改

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);
};

错误

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

http://ideone.com/cMfEf

修改

哦,我明白了。这是断言失败时我应该得到的消息。但这无法给用户一些明智的信息。 :(

3 个答案:

答案 0 :(得分: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";
}

Ideone output for C++11

Ideone output for C++03

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

UPDATE2 :根据@sehe在聊天中的评论,您也可以为constexpr个功能执行此操作

constexpr bool is_power_of_two(int x)
{
    return x && ((x & (x-1)) == 0);
}

答案 1 :(得分:18)

现在,constexprbit twiddling hacks可以

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

答案 2 :(得分: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.");
};
相关问题