Home > Back-end >  Template class definition
Template class definition

Time:12-14

Does a class template -that takes integer parameter- define multiple classes for different integer inputs?

for ex: I applied the following code

template<int val>
class MyClass
{
public:
    static int var;
};

template<int val> int MyClass<val>::var = val;

int main(int argc, char* argv[])
{
    MyClass<5> a;
    MyClass<7> b;
    MyClass<9> c;

    std::cout << a.var <<  " , " << b.var <<  " , " << c.var << std::endl;

    return 0;
}

Output

5 , 7 , 9
  • does it mean that a class definition is created for every integer passed as template argument (as the static member variable is different every time) ?

  • Is there a way to check the generated class definitions? I tried to check map file and assembly code but no luck

CodePudding user response:

Yes, these will be 3 distinct types

You can for instance use C Insights to get an idea of the code that the compiler generates from class templates.

#include <iostream>

template<int val>
class MyClass
{
public:
    static int var;
};

/* First instantiated from: insights.cpp:14 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class MyClass<5>
{
  
  public: 
  static int var;
  // inline constexpr MyClass() noexcept = default;
};

#endif


/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class MyClass<7>
{
  
  public: 
  static int var;
  // inline constexpr MyClass() noexcept = default;
};

#endif


/* First instantiated from: insights.cpp:16 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class MyClass<9>
{
  
  public: 
  static int var;
  // inline constexpr MyClass() noexcept = default;
};

#endiint MyClass<9>::var = 9;


int main(int argc, char ** argv)
{
  MyClass<5> a = MyClass<5>();
  MyClass<7> b = MyClass<7>();
  MyClass<9> c = MyClass<9>();
  std::operator<<(std::operator<<(std::cout.operator<<(a.var), " , ").operator<<(b.var), " , ").operator<<(c.var).operator<<(std::endl);
  return 0;
}

edit: Altough you see CppInsight is not perfect, as it screwed up the instantiation of the static member variables.

  •  Tags:  
  • c
  • Related