c++ - 模板特化,在一个函数中具有多个模板参数

标签 c++ templates

我想要在一个函数中使用两个参数进行模板特化。这是代码示例。

#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();
}

有没有一种方法可以在一个函数中使 std::stringconst char * 的模板规范化。我想要这个,因为他们正在做同样的事情。

最佳答案

您可以根据类型使用特征来添加特定行为的间接性。

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

关于c++ - 模板特化,在一个函数中具有多个模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123528/

相关文章:

c++ - 错误 : no viable overloading with clang, 用 gcc 编译

c++ - 如何读取 .inf 文件?

c++ - 使用 open CV 的重映射函数和 CV_8SC1 类型的源图像

c# - VOIP:PC 到 PC 通话和 session

C++ "select"算法

c++ - 自动类模板?

C++ 模板函数获取错误的默认值

python - 在文件中存储带有函数调用的 f 字符串

c++ - 非特化 C++ 模板参数

C++ 如何修复 typedef 模板和类之间的依赖关系问题