前兩天看到了這篇文章 也來動(dòng)手實(shí)現(xiàn)一個(gè)。
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;