Home > front end >  Is there a way to access a template parameter outside the class?
Is there a way to access a template parameter outside the class?

Time:11-10

So I was trying to make a function that is required to access the template argument of that class and I don't want to put that function in the class itself.
Here is a example:

  template <class Type>
  class Node
  {
      public:
          Type Value;
          Type* ptr_next;
    
  };

  void element_output(Node<  /*template argument of the class*/>  * head)
  {
      while(head!=NULL)
      {
          std::cout << head->Value << "\n";
          head = head->ptr_next;
        
      }
  }

I tried using a template for that function but that didn't work. i was thinking of just overloading the Node template argument in the function parameter with all the types.But i knew there was bound to be a error had to be a error that will occur.

So what I think could work is like a getter and setter for the template parameters similar with constructors and private memebers.

CodePudding user response:

Make the function template:

template <typename T>
void element_output(Node<T>* head)
{
    while (head != nullptr)
    {
        std::cout << head->Value << "\n";
        head = head->ptr_next;
    }
}

CodePudding user response:

Assuming you didn't know about the function templates, you could explicitly create function overloads, say with

void element_output(Node<int>* head) { while ... }

void element_output(Node<double>* head) { while ... }

void element_output(Node<MyType>* head) { while ... }

Now you understand the natural templating mechanism

template<class Type> void element_output(Node<Type>* head) { while ... }

which you can specialize with element_output<int>, element_output<double>, element_output<MyType>...

Note that it is also possible to consider the argument to be a generic type,

template<class Type> void element_output(Type* head) { while ... }

and specialize with a Node type passed to element_output<Node<int> >, element_output<Node<double> >, element_output<Node<MyType> >...

  • Related