Anshuman
Anshuman

Reputation: 420

Template Specilization with multiple template parameters in one function

I want template specilization with two parameters in one function. Here is a sample of code.

#include <iostream>
#include <string>
template <typename T>
class Printer
{
    public:
    T value;
    Printer(T value)
    {
        this->value = value;
    }
    void print();
  };


template <typename T> void Printer<T>::print()
{
    std::cout << value << "\n";
}
template <> void Printer<std::string>::print()
{
    std::cout << "\"" << value <<"\"\n";
}

template <> void Printer<const char *>::print()
{
    std::cout << "\"" << value <<"\"\n";
}

int main()
{
    Printer<int> print1(2);
    Printer<std::string> print2("Printing string");
    Printer<const char *> print3("Printing char*");
    print1.print();
    print2.print();
    print3.print();
}

Is there a way I can make the template speciazation for std::string and const char * in one function. I want this because they are doing the same thing.

Upvotes: 2

Views: 52

Answers (1)

You can use traits to add indirection on the specific behavior, based on type.

#include <iostream>
#include <string>
template <typename T>
class Printer
{
    public:
    T value;
    Printer(T value)
    {
        this->value = value;
    }
    void print();
  };

template<typename T>
struct PrinterTypeTraits {
  static constexpr char* prefix  = "";
  static constexpr char* postfix = "";
};

template<>
struct PrinterTypeTraits<std::string> {
  static constexpr char prefix  = '\"';
  static constexpr char postfix = '\"';
};

template<>
struct PrinterTypeTraits<const char*> : PrinterTypeTraits<std::string> {};

template <typename T> void Printer<T>::print()
{
    using Traits = PrinterTypeTraits<T>;
    std::cout << Traits::prefix << value << Traits::postfix << '\n';
}


int main()
{
    Printer<int> print1(2);
    Printer<std::string> print2("Printing string");
    Printer<const char *> print3("Printing char*");
    print1.print();
    print2.print();
    print3.print();
    return 0;
}

Upvotes: 3

Related Questions