gpt4 book ai didi

c++ - 函数特化/重载规则示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:17 25 4
gpt4 key购买 nike

我知道你不能部分特化一个函数模板,我也理解典型的函数重载。

我需要帮助的是摸索以下 4 个 foo() 函数之间的区别。我希望其中一些是完全相同的东西的不同语法?

是否有知识渊博的人可以解释每个函数到底发生了什么,它是模板特化还是重载,以及 C++ 编译器如何确定调用什么?

//(1)
template<typename T>
void foo(T t)
{
cout << "template<T> foo(T) " << endl;
}

//(2)
template<>
void foo<int*>(int* l)
{
cout << "template<> foo<int*>(int*) " << endl;
}

//(3)
template<typename T>
void foo(T* l)
{
cout << "template<T> foo(T*) " << endl;
}

//(4)
void foo(int* l)
{
cout << "normal overload foo(int*) " << endl;
}

int main()
{
int x = 0;
foo(x);
foo(&x);
return 0;
}

程序输出:

template<T> foo(T)
normal overload foo(int*)

最佳答案

评论中的解释:

// the 1st primary function template, overloaded function template
template<typename T>
void foo(T t)

// full template specialization of the 1st function template with T = int*
template<>
void foo<int*>(int* l)

// the 2nd primary function template, overloaded function template
template<typename T>
void foo(T* l)

// non-template function, overloaded function
void foo(int* l)

int main()
{
int x = 0;
foo(x); // only match the 1st function template; the others take pointer as parameter
foo(&x); // call the non-template function, which is prior to templates in overload resolution
return 0;
}

查看有关 overload resolution 的更多详细信息和 explicit (full) template specialization .

关于c++ - 函数特化/重载规则示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594216/

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