我想创建一个模板类,该模板类为作为模板参数传递的每种类型实现print()
方法。
像这样:
class Interface
{
public:
virtual ~Interface() = default;
virtual void print(int) = 0;
virtual void print(double) = 0;
};
X x<int, double, Interface>;
class X
具有公共(public)方法void print()
,它可以工作。整个代码如下:
#include <iostream>
#include <type_traits>
struct Printer
{
void print(int i) {std::cout << i << std::endl; }
void print(double d) {std::cout << d << std::endl; }
};
class Interface
{
public:
virtual ~Interface() = default;
virtual void print(int) = 0;
virtual void print(double) = 0;
};
template <typename... Args>
class X;
template <typename Interface>
class X<Interface> : public Interface
{
static_assert(std::is_abstract<Interface>::value, "Last argument should be an interface");
public:
X(Printer printer) {}
using Interface::print;
};
template <typename Arg, typename... Args>
class X<Arg, Args...> : public X<Args...>
{
using Parent = X<Args...>;
public:
using Parent::print;
X(Printer printer_): Parent(printer), printer{printer_} {}
void print(Arg arg) override { printer.print(arg); }
private:
Printer printer;
};
int main()
{
Printer printer;
X<double, int, Interface> x(printer);
x.print(5);
}
如您所见,
class X
使用Printer
类,但问题是我想将Printer
作为模板参数...可能吗?怎么做?
最佳答案
抱歉,但是...我没看到问题(故事讲述者建议简化一下:将一个Printer
对象放在底例中)
template <typename...>
class X;
template <typename Printer, typename Interface>
class X<Printer, Interface> : public Interface
{
static_assert(std::is_abstract<Interface>::value,
"Last argument should be an interface");
public:
X (Printer p0) : printer{p0}
{ }
using Interface::print; // why?
protected:
Printer printer;
};
template <typename Printer, typename Arg, typename... Args>
class X<Printer, Arg, Args...> : public X<Printer, Args...>
{
using Parent = X<Printer, Args...>;
public:
using Parent::print;
using Parent::printer;
X(Printer printer_): Parent{printer_} {}
void print(Arg arg) override { printer.print(arg); }
};
// ....
X<Printer, double, int, Interface> x(printer);
主题外:注意:您正在使用未初始化的printer
X(Printer printer_): Parent(printer), printer{printer_} {}
我想你应该写Parent(printer_)
关于c++ - 模板类使用参数包时如何传递其他模板参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58712888/