基于指针类型的模板函数重载?

时间:2019-06-10 11:13:37

标签: c++ templates overloading

可以根据以下指针类型重载模板函数:

1)
template <class T>
void Function(T* ptr, char m)
{
    ...
}

2)
template <class T>
void Function(T i, char m)
{
    ...
}

在C ++中是否有效?

第2部分: 我可以根据以下指针类型来对函数进行模板化吗(忽略这种情况下的上述重载)?

3)
template<>
inline  Function<string>(string sptr, char m)
{
    ...
}

PS:当我尝试使用3来专门化模板1时,会出现编译错误。

2 个答案:

答案 0 :(得分:2)

根据指针类型重载模板是完全合法的。当相同的功能模板专业化匹配多个重载功能模板时,将对重载功能模板进行偏序以选择最佳匹配。

在这种情况下,它是由overload resolution完成的,以调用函数模板专门化功能。有关更多信息,请参见Function template

即使您的功能模板专业化完全有效。

引用cppreference's Function template

具体来说,在以下情况下会发生部分排序:

  1. overload resolution用于调用功能模板专业化
template<class X> void f(X a);
template<class X> void f(X* a);
int* p;
f(p);
  1. 使用address of a function template specialization
template<class X> void f(X a);
template<class X> void f(X* a);
void (*p)(int*) = &f;
  1. 当选择功能模板特化placement operator delete来匹配新的展示位置运算符
  2. friend function declarationexplicit instantiation或显式专门化指功能模板专门化时
template<class X> void f(X a);  // first template f
template<class X> void f(X* a); // second template f
template<> void f<>(int *a) {} // explicit specialization
 // template argument deduction comes up with two candidates:
 // foo<int*>(int*) and f<int>(int*)
 // partial ordering selects f<int>(int*) as more specialized

答案 1 :(得分:1)

是的,拥有这两个模板是完全合法的,并且它们会彼此过载。专业化也完全合法。