使用模板化方法删除类型

我有许多类都需要一个未指定类型的对象并返回一个固定类型的结果。此外,这些对象是模板化的,它改变了结果的计算。我想将这些对象隐藏在一个通用接口后面。下面的例子应该说清楚。 struct Work是接口,并存在多个类如struct WorkImpl。此外还有多种类型,如struct Astruct B,它们相互作用。在我的情况下,它们也是模板化的,不能是多态的。问题是如何将工作调用“转发”给WorkImpl对象?使用模板化方法删除类型

#include <iostream> 

struct Result

{

};

struct Work

{

virtual ~Work() { }

template <typename U>

// virtual Result work(const U& u) = 0; // this is not possible, of course!

Result work(const U& u) { std::cout << "Work" << std::endl; }

};

struct B

{

};

struct A

{

A& operator =(const B& b) { return *this; }

Result result() { return Result(); }

};

template <typename T>

struct WorkImpl : public Work

{

template <typename U>

Result work(const U& u)

{

std::cout << "WorkImpl" << std::endl;

T t;

t = u;

return t.result();

}

};

int main()

{

Work* w = new WorkImpl<A>();

w->work(B());

return 0;

}

回答:

我真的不知道问题是什么。

代码编译。

你不想多态性但

  • 你忘了静态多态性也多态性
  • 你无偿使用继承,尽管有所有
没有统一的接口

我建议只从界面中获取参数。键入擦除的最简单方法是使用std::function<Result()>并完成。

如果需要,我可以添加一个小样本。

以上是 使用模板化方法删除类型 的全部内容, 来源链接: utcz.com/qa/258768.html

回到顶部