函数特化/重载规则示例

Jor*_*dan 5 c++ templates overloading template-specialization overload-resolution

我理解你不能部分专门化一个函数模板,我也理解典型的函数重载.

我需要帮助的地方是了解下面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;
}
Run Code Online (Sandbox Code Playgroud)

节目输出:

template<T> foo(T)
normal overload foo(int*)
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

评论中的解释:

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

查看有关重载决策显式(完整)模板特化的更多详细信息.