90

我知道语言规范禁止函数模板的部分专业化。

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

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!
4

4 回答 4

59

AFAIK 在 C++0x 中发生了变化。

我想这只是一个疏忽(考虑到您总是可以通过将函数作为static类的成员来使用更详细的代码来获得部分专业化效果)。

如果有,您可以查找相关的 DR(缺陷报告)。

编辑:检查这一点,我发现其他人也相信这一点,但没有人能够在标准草案中找到任何这样的支持。这个 SO 线程似乎表明C++0x 不支持函数模板的部分特化

编辑2:只是我所说的“将函数作为static类的成员”的一个例子:

#include <iostream>
using namespace std;

// 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!

void say( char const s[] ) { std::cout << s << std::endl; }

namespace detail {
    template< class T, class U >
    struct F {
        static void impl() { say( "1. primary template" ); }
    };

    template<>
    struct F<int, char> {
        static void impl() { say( "2. <int, char> explicit specialization" ); }
    };

    template< class T >
    struct F< char, T > {
        static void impl() { say( "3. <char, T> partial specialization" ); }
    };

    template< class T >
    struct F< T, int > {
        static void impl() { say( "4. <T, int> partial specialization" ); }
    };
}  // namespace detail

template< class T, class U >
void f() { detail::F<T, U>::impl(); }    

int main() {
    f<char const*, double>();       // 1
    f<int, char>();                 // 2
    f<char, double>();              // 3
    f<double, int>();               // 4
}
于 2011-02-24T07:18:45.040 回答
19

好吧,你真的不能做部分函数/方法的专门化,但是你可以做重载。

template <typename T, typename U>
T fun(U pObj){...}

// acts like partial specialization <T, int> AFAIK 
// (based on Modern C++ Design by Alexandrescu)
template <typename T>
T fun(int pObj){...} 

就是这样,但我不知道它是否满足你。

于 2015-01-27T10:06:33.597 回答
15

一般来说,完全不建议专门化函数模板,因为重载的麻烦。这是来自 C/C++ 用户杂志的一篇好文章:http ://www.gotw.ca/publications/mill17.htm

它包含对您问题的诚实答案:

一方面,你不能对它们进行部分专业化——几乎只是因为语言说你不能。

于 2011-02-24T07:33:17.053 回答
11

由于您可以部分专门化类,因此可以使用仿函数:

#include <iostream>

template < typename dtype , int k > struct fun
{
 int operator()()
 {
  return k ;
 }
} ;

template < typename dtype > struct fun < dtype , 0 >
{
 int operator()()
 {
  return 42 ;
 }
} ;

int main ( int argc , char * argv[] )
{
 std::cout << fun<float,5>()() << std::endl ;
 std::cout << fun<float,0>()() << std::endl ;
}
于 2016-04-22T17:03:49.793 回答