reinaldo
reinaldo

Reputation: 5918

Const receiving a var, i cant pass it to a template

What I want to do is:

int const bitsPerInt = log2(X);
bitset<bitsPerInt>  bits(a random number...);

but I get this error:

'bitsPerInt' cannot appear in a constant expression error: template argument 1 is invalid

Upvotes: 4

Views: 84

Answers (2)

legends2k
legends2k

Reputation: 33004

If you really need this to work, make your own log2 that works in compile-time and pass it to bitset's template argument.

constexpr unsigned Log2(unsigned n, unsigned p = 0) {
    return (n <= 1) ? p : Log2(n / 2, p + 1);
}

constexpr size_t bitCount = Log2(X);
std::bitset<bitCount> bits;

Live example.


Here's the solution using template meta-programming i.e. without using constexpr:

template<int N,unsigned int P=0>
struct Log2 { enum { value = Log2<N/2,P+1>::value }; };

template <unsigned p>
struct Log2<0, p> { enum { value = p }; };

template <unsigned p>
struct Log2<1, p> { enum { value = p }; };

std::bitset<Log2<4>::value> bits;

Live example.

This version should work in both C++03 and C++11; however, if you've access to C++11, I'd still recommend the constexpr way since it's cleaner (easier to understand).

Upvotes: 4

Eric Fortin
Eric Fortin

Reputation: 7603

Template parameter needs to be known(and constant if it is a value and not a type) at compile time. This is how templates work in C++. Templates actually generate real code for each specific version of the generic code.

Upvotes: 3

Related Questions