Narrowing a template template without a template in template recursion

I have the following code that should calculate the number of bits in a byte at compile time.

template<unsigned char c, size_t I>
struct char_bit
{
    static constexpr size_t get() noexcept {
        return c > 0 ? char_bit<c << 1, I + 1>::get() : I
    }
};

int main()
{   
    std::cout << char_bit<1, 0>::get();
}

Turning 1to the parameter unsigned char, I expect to get the final result of 8, since it will shift left 8 times until the char becomes 0.

However, compiling with Clang 3.7.1, I get a compilation error:

error: a non-type template argument is evaluated to 256, which cannot be narrowed to unsigned char '[-WC ++ 11-narrowing]

Why is this happening? How can i fix this?

+4
source share
4 answers

: char , . , ( ):

#include <iostream>
using namespace std;

template<unsigned char c, size_t I>
struct char_bit
{
    static constexpr size_t get() noexcept {
        return char_bit< (c >> 1), I + 1>::get();
    }
};

template<size_t I>
struct char_bit<0, I>
{
    static constexpr size_t get() noexcept {
        return I;
    }
};


int main()
{   
    constexpr unsigned char c = static_cast<unsigned char>(-1);
    std::cout << char_bit<c, 0>::get();
}
+3

:

#include <climits>

int main() {
    std:cout << CHAR_BIT << std::endl;
}
+2

OP , , :

char_bit<(unsigned char)(c << 1), I + 1>::get()
+1

, . , , .

template<unsigned char c, size_t I>
struct char_bit
{
    static constexpr size_t get() noexcept {
        return char_bit<(c << 1), I + 1>::get();
    }
};

template <size_t I>
struct char_bit<0, I>
{
    static constexpr size_t get() noexcept { return I; }
};
0

All Articles