Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function static variable

Tags:

c++

templates

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;
}

When I call get_component_type_id with BaseClass 10 times, I get the same id. That works perfectly.

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?

like image 919
Daniel Ribeiro Avatar asked Dec 25 '22 04:12

Daniel Ribeiro


2 Answers

This is because an instantiation of a template, once instantiated, has nothing to do with a second instantiation of the same template. The two are seperate entities and get their own static variable.

PS: Here is a video where this occurs in an example: CppCon 2015: Arthur O'Dwyer “Lambdas from First Principles: A Whirlwind Tour of C++"”. The example starts aroung 6:00

like image 114
463035818_is_not_a_number Avatar answered Jan 08 '23 07:01

463035818_is_not_a_number


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>();
}
like image 30
user2296177 Avatar answered Jan 08 '23 08:01

user2296177