本文介绍了具有模板化类型的模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想使用以下函数专门化类模板: template< typename T& class Foo { public: static int bar(); }; 函数没有参数,将返回基于Foo类型的结果。 (在这个玩具示例中,我们返回类型的字节数,但是在实际应用中我们要返回一些元数据对象。)专用化适用于完全指定的类型: // specialization 1:works template<> int Foo< int> :: bar(){return 4; } // specialization 2:works template<> int Foo< double> :: bar(){return 8; } // specialization 3:works typedef pair< int,int> IntPair; 模板<> int Foo< IntPair> :: bar(){return 2 * Foo< int> :: bar() } 但是,我想将其推广到依赖于(其他)模板参数的类型。 添加以下特化会产生编译错误(VS2005): // specialization 4:ERROR! 模板<> template< typename U,typename V> int Foo< std :: pair< U,V> > :: bar(){return Foo U&:: bar()+ Foo V :: :: bar(); } 我假设这不是合法的C ++,但是为什么? 解决方案部分专业化仅对类而不是函数有效。 解决方法: template< typename U,typename V& class Foo< std :: pair< U,V& > { public: static int bar(){return Foo< U> :: bar()+ Foo< V> :: bar } }; 如果你不想完全专门化类,请使用辅助struct 模板< class T> struct aux { static int bar(); }; template<> int aux< int> :: bar(){return 4; } template<> int aux< double> :: bar(){return 8; } template< typename U,typename V> struct aux< std :: pair< U,V> > { static int bar(){return Foo< U> :: bar()+ Foo< V> :: bar } }; template< class T> class Foo:aux< T> { // ... }; I want to specialize a class template with the following function:template <typename T>class Foo{public: static int bar();};The function has no arguments and shall return a result based on the type of Foo. (In this toy example, we return the number of bytes of the type, but in the actual application we want to return some meta-data object.)The specialization works for fully specified types:// specialization 1: workstemplate <>int Foo<int>::bar() { return 4; }// specialization 2: workstemplate <>int Foo<double>::bar() { return 8; }// specialization 3: workstypedef pair<int, int> IntPair;template <>int Foo<IntPair>::bar() { return 2 * Foo<int>::bar(); }However, I would like to generalize this to types that depend on (other) template parameters themselves.Adding the following specialization gives a compile-time error (VS2005):// specialization 4: ERROR!template <>template <typename U, typename V>int Foo<std::pair<U, V> >::bar() { return Foo<U>::bar() + Foo<V>::bar(); }I am assuming this is not legal C++, but why? And is there a way to implement this type of pattern elegantly? 解决方案 Partitial specialization is valid only for classes, not functions.Workaround:template <typename U, typename V>class Foo<std::pair<U, V> > {public: static int bar() { return Foo<U>::bar() + Foo<V>::bar(); }};If you does not want to specialize class fully, use auxiliary structtemplate<class T>struct aux { static int bar();};template <>int aux <int>::bar() { return 4; }template <>int aux <double>::bar() { return 8; }template <typename U, typename V>struct aux <std::pair<U, V> > { static int bar() { return Foo<U>::bar() + Foo<V>::bar(); }};template<class T>class Foo : aux<T> { // ...}; 这篇关于具有模板化类型的模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 18:39