How to traversal recursive template class

General Tech Bugs & Fixes 2 years ago

3 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 29 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I want to traversal multiple depth template class. in C++98 (before c++11).

pesudo code.

template<typename T>
std::string find_type(T *ptr);
template <>
std::string find_type<std::string>(int *ptr)
{
  return "string";
}
template <>
std::string find_type<std::list>(std::list *ptr)
{
  return "list";
}
template <>
std::string find_type<std::vector>(std::vector *ptr)
{
  return "vector";
}

template<T>
std::string somefunction(T *ptr)
{
 if(T is template class)
   return find_type + " " + somefunction(ptr);
else
 return find_type(ptr);
}

I want to below result :

 std::list<std::string> test;
somefunction(test) -> I NEED "list string";

 std::list<std::vector<std::string> > test2;
somefunction(test) -> I NEED "list vector string";

How can I do it?

profilepic.png
manpreet 2 years ago

 

I believe that this result can't be achieved via template function specialization (since partial function specializations isn't allowed). But it can be achieved via template class specializations:

#include 
#include 
#include <string>

template <typename T>
struct TypePrinter;

template <typename T>
struct TypePrinter<std::vector<T> >
{
    static std::string print()
    {
        return "vector " + TypePrinter<T>::print();
    }
};

template <typename T>
struct TypePrinter<std::list<T> >
{
    static std::string print()
    {
        return "list " + TypePrinter<T>::print();
    }
};

template <>
struct TypePrinter<std::string>
{
    static std::string print()
    {
        return "string";
    }
};

int main()
{
    std::string i = TypePrinter<std::list<std::string> >::print();
    std::string ii = TypePrinter<std::list<std::vector<std::string> > >::print();
}

3 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.