当从全局命名空间获取模板名称时,您可以使用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]
我原本打算将其中一部分放入匿名命名空间中,以实际赋予::
非平凡的含义,但这似乎已经足够了,所以我没有这样做。
template
为前缀的名称应该是一个模板标识符,或者该名称应该引用一个类模板。” ::template function_template
都不是,因此它应该是非法的。 - T.C.
function_template
是全局命名空间的成员,这段代码可以在没有它的情况下编译。 - template boy