为什么功能模板不能部分专业化?

我知道语言规范禁止对功能模板进行部分专业化。


我想知道为什么它禁止这样做的理由?它们没有用吗?


template<typename T, typename U> void f() {}   //allowed!

template<> void f<int, char>()            {}   //allowed!

template<typename T> void f<char, T>()    {}   //not allowed!

template<typename T> void f<T, int>()     {}   //not allowed!


MYYA
浏览 489回答 3
3回答

湖上湖

我想这只是一个疏忽(考虑到通过将函数作为static类的成员,您总是可以使用更详细的代码来获得部分专业化效果)。您可能会查找相关的DR(缺陷报告)(如果有)。编辑:检查这一点,我发现其他人也相信这一点,但是没有人能够在标准草案中找到任何这样的支持。该SO线程似乎表明C ++ 0x不支持功能模板的部分专业化。编辑2:只是我的意思是“将函数作为static类的成员放置”的一个示例:#include <iostream>using namespace std;// template<typename T, typename U> void f() {}&nbsp; &nbsp;//allowed!// template<> void f<int, char>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {}&nbsp; &nbsp;//allowed!// template<typename T> void f<char, T>()&nbsp; &nbsp; {}&nbsp; &nbsp;//not allowed!// template<typename T> void f<T, int>()&nbsp; &nbsp; &nbsp;{}&nbsp; &nbsp;//not allowed!void say( char const s[] ) { std::cout << s << std::endl; }namespace detail {&nbsp; &nbsp; template< class T, class U >&nbsp; &nbsp; struct F {&nbsp; &nbsp; &nbsp; &nbsp; static void impl() { say( "1. primary template" ); }&nbsp; &nbsp; };&nbsp; &nbsp; template<>&nbsp; &nbsp; struct F<int, char> {&nbsp; &nbsp; &nbsp; &nbsp; static void impl() { say( "2. <int, char> explicit specialization" ); }&nbsp; &nbsp; };&nbsp; &nbsp; template< class T >&nbsp; &nbsp; struct F< char, T > {&nbsp; &nbsp; &nbsp; &nbsp; static void impl() { say( "3. <char, T> partial specialization" ); }&nbsp; &nbsp; };&nbsp; &nbsp; template< class T >&nbsp; &nbsp; struct F< T, int > {&nbsp; &nbsp; &nbsp; &nbsp; static void impl() { say( "4. <T, int> partial specialization" ); }&nbsp; &nbsp; };}&nbsp; // namespace detailtemplate< class T, class U >void f() { detail::F<T, U>::impl(); }&nbsp; &nbsp;&nbsp;int main() {&nbsp; &nbsp; f<char const*, double>();&nbsp; &nbsp; &nbsp; &nbsp;// 1&nbsp; &nbsp; f<int, char>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 2&nbsp; &nbsp; f<char, double>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 3&nbsp; &nbsp; f<double, int>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 4}

撒科打诨

好吧,您确实不能执行部分函数/方法专门化,但是可以执行重载。template <typename T, typename U>T fun(U pObj){...}// acts like partial specialization <T, int> AFAIK&nbsp;// (based on Modern C++ Design by Alexandrescu)template <typename T>T fun(int pObj){...}&nbsp;是这样,但我不知道它是否满足您。
打开App,查看更多内容
随时随地看视频慕课网APP