前两天看到了这篇文章 也来动手实现一个。
template<size_t binary>
struct bin2dec {
template<size_t b, size_t pos>
struct helper {
static_assert(b % 10 == 0 || b % 10 == 1, "binary should be 0 or 1");
static const size_t value = ((b % 10) << pos) + helper<b / 10, pos + 1>::value;
};
template<size_t pos>
struct helper<0, pos> { static const size_t value = 0; };
static const size_t value = helper<binary, 0>::value;
};
用法:
std::cout << bin2dec<111101001>::value << endl;