gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:39:29 26 4
gpt4 key购买 nike

模板函数是否可以根据指针类型进行重载,如下所示:

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 时,出现编译错误。

最佳答案

根据指针类型重载模板是完全合法的。当相同的函数模板特化匹配多个重载函数模板时,部分排序重载函数模板被执行以选择最佳匹配。

在这种情况下,它是由 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 declaration , 一个 explicit 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

关于c++ - 基于指针类型的模板函数重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56525304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com