模板元编程 二进制转换

前两天看到了这篇文章 也来动手实现一个。

template
struct bin2dec {
    template
    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::value;
    };
    
    template
    struct helper<0, pos> { static const size_t value = 0; };
    
    static const size_t value = helper::value;
};

用法:
std::cout << bin2dec<111101001>::value << endl;

你可能感兴趣的:(模板元编程 二进制转换)