I’m experimenting with templates and I wrote this simple class method:
void Decimal::toBinary(size_t bits) {
// decimalNumber being a class private variable (long double)
std::bitset< bits > result(decimalNumber);
std::cout << result << std::endl;
}
I’m trying to pass size_t bits function argument to the bitset template.
According to C++ Bitset Reference the implementations takes indeed a size_t argument:
template < size_t N > class bitset;
However, I’m getting
src/decimal.cc:11: error: ‘bits’ cannot appear in a constant-expression
src/decimal.cc:11: error: template argument 1 is invalid
src/decimal.cc:11: error: invalid type in declaration before ‘(’ token
I suppose I’m not able to do this… any workarounds?
Templates are a compile-time feature, not a run-time feature. If the number of different sizes you are going to support is limited, e.g., because you support 8, 16, and 32 bits, you can
switchand delegate:BTW, don’t use
std::endl. If you really mean to flush the stream usestd::flush.