gpt4 book ai didi

c++ - 有没有理由使用 "::template"?

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

从全局命名空间获取模板名称时,您可以使用 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]

我打算将其中的一些内容填充到一个匿名命名空间中,以实际为 :: 带来重要意义,但这似乎已经足够了,所以我将其遗漏了。

关于c++ - 有没有理由使用 "::template"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007081/

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