c – 模板类,函数专业化
发布时间:2020-12-16 03:45:18 所属栏目:百科 来源:网络整理
导读:我想要一个看起来像我下面的模板类.然后,我想要一个带有模板特化的函数,具体取决于CLASS模板参数.我该如何工作?我意识到我提供的代码在很多层面都是错误的,但它只是为了说明这个概念. template typename _T,size_t numclass Foo{ // If num == 1,I want to
我想要一个看起来像我下面的模板类.然后,我想要一个带有模板特化的函数,具体取决于CLASS模板参数.我该如何工作?我意识到我提供的代码在很多层面都是错误的,但它只是为了说明这个概念.
template <typename _T,size_t num> class Foo { // If num == 1,I want to call this function... void Func<_T,1>() { printf("Hi!"); } // Otherwise,I want to call this version. void Func<_T,num>() { printf("Hello world!"); } }; 解决方法struct Otherwise { }; template<size_t> struct C : Otherwise { }; // don't use _Uppercase - those names are reserved for the implementation // (i removed the '_' char) template <typename T,size_t num> class Foo { public: void Func() { Func(C<num>()); } private: // If num == 1,I want to call this function... void Func(C<1>) { printf("Hi 1!"); } // If num == 2,I want to call this function... void Func(C<2>) { printf("Hi 2!"); } // Otherwise,I want to call this version. void Func(Otherwise) { printf("Hello world!"); } //// alternative otherwise solution: // template<size_t I> // void Func(C<I>) { .. } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |