问题描述
我有一个模板函数给我一个唯一的id基于 typename
传递给它,像这样:
I have a template function to give me a unique id based on the typename
passed to it, like this:
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;
}
当我调用 get_component_type_id
与 BaseClass
10次,我得到相同的id。
When I call get_component_type_id
with BaseClass
10 times, I get the same id. That works perfectly.
但是,如果我将一个子类传递给该函数,我想获得相同的id。当我用 ChildClass
调用它时,我得到一个不同的id。为什么呢?
However, I want to get the same id as well if I pass a child class to that function. When I call it with ChildClass
, I get a different id. Why is that?
推荐答案
您可以尝试添加一个调用 get_component_type_id $ c>
组件
作为模板参数,当实际 T
是
。
You can try adding a function that calls
get_component_type_id()
with Component
as the template argument when the actual T
is a child of Component
.
template<class T>
auto fn() noexcept
{
using type = std::conditional_t<std::is_base_of<Component, T>::value, Component, T>;
return get_component_type_id<type>();
}
这篇关于模板函数静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!