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

Naw*_*waz 78 c++ language-design partial-specialization template-specialization function-templates

我知道语言规范禁止功能模板的部分特化.

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

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!
Run Code Online (Sandbox Code Playgroud)

Che*_*Alf 55

在C++ 0x中更改的AFAIK.

我想这只是一个疏忽(考虑到你可以通过将函数作为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
}
Run Code Online (Sandbox Code Playgroud)

  • 这在C++ 0x中没有改变.我也怀疑它的实用性.您总是可以重载模板并使用部分*排序*. (3认同)
  • 后期更新:即使在八年后的C++17中也没有改变,并且似乎也没有进入C++20。但看不出任何原因... (2认同)

Mic*_*l W 14

好吧,你真的不能做部分功能/方法专业化,但你可以做重载.

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){...} 
Run Code Online (Sandbox Code Playgroud)

这是方式,但我不知道它是否满足你.

  • 哇,我的脑海里充满了模板,以至于我真的忘记了事情是多么简单:) (2认同)
  • 不幸的是,当您想在部分专门化函数后传递可变参数时,情况并非如此.. :( (2认同)

Geo*_*kov 13

一般情况下,由于存在重载问题,因此不建议专门设计功能模板.以下是C/C++用户期刊的一篇好文章:http://www.gotw.ca/publications/mill17.htm

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

首先,你不能对它们进行部分专业化 - 几乎只是因为语言说你做不到.

  • 这篇文章除了提到一次之外,不是关于部分专业化的。 (3认同)

小智 10

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

#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 ;
}
Run Code Online (Sandbox Code Playgroud)