C++ 可变模板参数初探

C++ 可变模板参数初探,第1张

C++ 可变模板参数初探

参考:泛化之美–C++11可变模版参数的妙用
根据参考资料,简单验证了一下模板函数、模板类中总共4种情况。
4种情况的详细讲解直接看参考资料吧,大佬写的非常好,在这里本人就不瞎说了。

#include 

//用哪个就取消相应注释
#define func_recursion // 可变模板参数函数——递归法
//#define func_comma     // 可变模板参数函数——逗号表达式法

//#define class_recursion // 可变模板参数类——递归法
//#define class_inherit   // 可变模板参数类——继承法



#ifdef func_recursion 

template
void outprint(last_type t) { std::cout << t << std::endl; }


template
void outprint(first_type t, rest_types...datas) {
    std::cout << t << std::endl;
    outprint(datas...);
}
#endif


#ifdef func_comma

template
void outp(last_type t) { std::cout << t << std::endl; }


template
void outprint(rest_types...datas) {
    int temp[] = {(outp(datas),0)...};
}
#endif



#ifdef class_recursion


template 
class type_show{
public:
    static void print_type() {
        first_type temp;
        std::cout << typeid(temp).name() << std::endl;
        type_show::print_type();
    }
};


template 
class type_show {
public:
    static void print_type() {
        last_type temp;
        std::cout << typeid(temp).name() << std::endl;
    }
};

#endif


#ifdef class_inherit


template 
class type_show :public type_show{
public:
    type_show() {
        first temp;
        std::cout << typeid(temp).name() << std::endl; // 在构造函数中输出被展开的类型名
    }
};


template 
class type_show {
public:
    type_show() {
        last_types temp;
        std::cout << typeid(temp).name() << std::endl;
    }
};

#endif

int main()
{

#if (defined func_recursion) || (defined func_comma)
    outprint(1, 2, 3, "1234");
#endif

#ifdef class_recursion
    type_show::print_type();
#endif

#ifdef class_inherit
    // 连续继承时构造函数的执行顺序是倒着的
    type_show temp;
#endif


    system("pause");
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4653863.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-06
下一篇 2022-11-06

发表评论

登录后才能评论

评论列表(0条)

保存