是否有使用"::template"的理由?(涉及IT技术)

5

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

template <class T> void function_template();

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

int main() { h<int>(); }

但是这段代码可以在没有它的情况下编译。有哪些情况下可能希望这样做呢?

@KerrekSB 但是 function_template全局命名空间的成员,这段代码可以在没有它的情况下编译。 - template boy
哦,抱歉,你指的是全球版本 - 那就算了。 - Kerrek SB
1个回答

8
我可以想到一个地方,但我认为它不太常见:
#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]

我原本打算将其中一部分放入匿名命名空间中,以实际赋予::非平凡的含义,但这似乎已经足够了,所以我没有这样做。


[temp.names]/p5说:“以关键字template为前缀的名称应该是一个模板标识符,或者该名称应该引用一个类模板。” ::template function_template 都不是,因此它应该是非法的。 - T.C.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接