Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在一个函数中使用多个模板参数的模板专用化_C++_Templates - Fatal编程技术网

C++ 在一个函数中使用多个模板参数的模板专用化

C++ 在一个函数中使用多个模板参数的模板专用化,c++,templates,C++,Templates,我想要在一个函数中指定两个参数的模板。下面是一个代码示例 #include <iostream> #include <string> template <typename T> class Printer { public: T value; Printer(T value) { this->value = value; } void print(); }; template <

我想要在一个函数中指定两个参数的模板。下面是一个代码示例

#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();
}
#包括
#包括
模板
类打印机
{
公众:
T值;
打印机(T值)
{
这个->值=值;
}
作废打印();
};
模板无效打印机::打印()
{

std::cout您可以使用traits根据类型在特定行为上添加间接性

#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;
}
#包括
#包括
模板
类打印机
{
公众:
T值;
打印机(T值)
{
这个->值=值;
}
作废打印();
};
模板
结构PrinterTypeTraits{
静态constexpr char*前缀=”;
静态constexpr char*postfix=“”;
};
模板
结构PrinterTypeTraits{
静态constexpr字符前缀=“\”;
静态constexpr char后缀=“\”;
};
模板
结构PrinterTypeTraits:PrinterTypeTraits{};
模板无效打印机::打印()
{
使用Traits=PrinterTypeTraits;
标准::cout