模板函数静态变量

Dan*_*iro 4 c++ templates

我有一个模板函数,可以根据typename传递给它的参数给我一个唯一的 id,如下所示:

template<typename T>
inline std::size_t get_component_type_id() noexcept
{
    static_assert(std::is_base_of<Component, T>::value, "T must be of type Component.");

    static size_t uniqueComponentId{__INTERNAL__::getUniqueComponentId()};

    return uniqueComponentId;
}
Run Code Online (Sandbox Code Playgroud)

当我调用get_component_type_id10BaseClass次时,我得到相同的 id。效果很好。

但是,如果我将子类传递给该函数,我也想获得相同的 id。当我用 调用它时ChildClass,我得到一个不同的 id。这是为什么?

for*_*818 5

这是因为模板的实例化一旦实例化,就与同一模板的第二次实例化无关。两者是独立的实体并拥有自己的静态变量。

\n\n

PS:这里有一个视频,示例中出现了这种情况:CppCon 2015: Arthur O\'Dwyer \xe2\x80\x9cLambdas from First Principles: A Whirlwind Tour of C++"\xe2\x80\x9d。示例从 6 开始: 00

\n