C++ 模板传参

在C++中模板可以用来传递参数, 而且可以给参数设定默认值. 下面看一个例子:

#include <iostream>
#include <type_traits>

template <bool cond, typename Then, typename Else> struct IF;

template <typename Then, typename Else> struct IF<true, Then, Else> {
    using result = Then;
};

template <typename Then, typename Else> struct IF<false, Then, Else> {
    using result = Else;
};

template <bool cond, typename Then, typename Else> struct static_const_value {
    static const auto value = IF<(cond), Then, Else>::result::value;
};

template <int a, int b, int c = 0>
class Any {
    public:
        static const int value = a + b + c;
};

int main(void) {
    static_assert(static_const_value<10 - 1 == 9, Any<0, 1>, Any<0, 2>>::value == 1, "failed");
    static_assert(static_const_value<10 - 1 != 9, Any<0, 1>, Any<0, 2>>::value == 2, "failed");
}

上面的例子通过模板特化模拟 if 语句. 通过模板参数Any 传递参数, 实现对变量 Any::value 赋值, 而且所有的计数都是在编译期执行的. 如果觉得有帮助,可以扫描右边的微信打赏码支持一下.

Leave a Reply

Your email address will not be published. Required fields are marked *