有理由使用"::template"吗?

Is there ever a reason to use "::template"?

本文关键字:template 有理由      更新时间:2023-10-16

从全局命名空间获取模板名称时,可以使用 template 关键字:

template <class T> void function_template();
template <class T>
void h()
{
    ::template function_template<T>();
}
int main() { h<int>(); }

但是这段代码可以在没有它的情况下进行编译。在什么情况下可能想要这样做?

我可以想到一个地方,但我几乎不认为它会很常见:

#include <iostream>
// simpile function template
template<class T>
void function_template(T)
{
    std::cout << __PRETTY_FUNCTION__ << 'n';
}
// overload (NOT specialized)
void function_template(int value)
{
    std::cout << __PRETTY_FUNCTION__ << 'n';
}
int main()
{
    function_template(0);               // calls overload
    ::function_template(0);             // calls overload
    ::template function_template(0);    // calls template, deduces T
}

输出

void function_template(int)
void function_template(int)
void function_template(T) [T = int]

我打算将其中一些塞进一个匿名命名空间中,以实际为::带来非平凡的意义,但这似乎已经足够了,所以我省略了它。