![](/img/trans.png)
[英]Clang fails to compile template function in a template class specialization, which has *distinct return type* from the template declaration
[英]Template declaration in function declaration that already has a return type?
所以我正在关注 2D 游戏的 C++/SDL2 编程教程系列。 我一直在关注这个视频,他写了这段代码。
using ComponentID = std::size_t;
inline ComponentID getComponentID()
{
static ComponentID lastID = 0;
return lastID++;
}
template <typename T> inline ComponentID getComponentID() noexcept
{
static ComponentID typeID = getComponentID();
//typeID below is being used like a function???
return typeID(); //<- error and won't compile, I believe this was a typo
}
我不明白为什么template<typename T>
被放在那一行用于inline ComponentID getComponentID() noexcept
。 为什么会在那里? 显然,模板声明后没有分号,所以我想它可以放在同一行,但为什么呢? 有什么我想念的吗? 我还没有完成视频,因为这让我感到困惑,不想只是浏览整个视频复制代码而不理解它。 任何提示?
编辑:我知道模板是如何工作的,我不需要这方面的课程。 但是在该函数的声明中已经有一个返回类型,这就是我要问的。 不是让陌生人教我 C++ 语言。
template <typename T> inline ComponentID getComponentID() noexcept
ComponentID aka std::size_t
已经指定了返回类型不是吗? T
的定义放在同一行上,不在该函数中使用。 这就是我要问的。 我错过了什么? 因为我不认为一个函数可以有多种返回类型。 因此,既然它不是返回类型,也没有在函数本身中使用,也没有用作参数的类型,那么它在此上下文中的用途是什么?
目标是按类型拥有唯一的增量 ID。
所以与
ComponentID getComponentID()
{
static ComponentID lastID = 0;
return lastID++;
}
template <typename T>
ComponentID getComponentID() noexcept
{
static ComponentID typeID = getComponentID();
return typeID; // () was a typo indeed
}
我们将有
struct Component1 {};
struct Component2 {};
getComponent<Component1>(); // Will return 0
getComponent<Component2>(); // will return 1
getComponent<Component1>(); // Will return 0
getComponent<Component2>(); // will return 1
模板用于调整函数或类以支持多个内置或自定义类型。 通过这样做,您可以在同一代码中使用不同的类型,最终减少重复代码。
想象一下,您的 getComponentID() 必须返回一个 int 并且在另一种情况下需要它返回一个 double。 如果getcomponentid()
不是模板函数,则必须重载该函数以处理 int 和 double 返回类型。 由于您使用的是模板,因此您无需处理它。 编译器会为你处理。
但是需要注意的一件事是,模板会减慢您的编译时间。
http://www.cplusplus.com/doc/oldtutorial/templates/
跟进您的编辑:
他没有返回模板类型。 而不是做;
template<typename T>
inline ComponentID getComponentID()
{
...
...
}
他将所有内容都放在一行中。如下。
template <typename T> inline ComponentID getComponentID()
你真的,来自网络的一些陌生人-.-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.