在 C++ 中,我有一个基类参数化超过 1 种类型,对于每个具有特定附加结构的子类,我想将该子类映射到另一种类型,这也是同一基类的子类。然而,我的代码产生了一个错误,编译器不会按照我的意图去做。所以
- 我应该如何修复我的代码以获得
int main()
工作? - 模板功能可以吗
wrap
写入Base<A>* wrap(Sub& )
, 返回Wrap<A, Sub>
如果参数有一个方法Sub::g(A& )
, 或者只是Sub
如果不是(身份)?
.
using uint = unsigned int;
// for each type A, there is a base class Base<A>
template <typename A>
class Base
{
public:
virtual void f(A& ) = 0;
};
// for each type A, and for each type Sub having methods
// Sub::f(A& ) and Sub::g(A& ), there is a special subclass
// of Base<A>, with the name Wrap<A, Sub>.
//
// NOTE: the type Sub has more structure, it is actually
// a subclass of Base<A>.
template <typename A, typename Sub>
class Wrap : public Base<A>
{
friend Wrap<A, Sub>* wrap(Sub& sub);
public:
virtual void f(A& a) override
{
// ... do stuff on 'a', using Sub::f() and Sub::g() ...
}
private:
Wrap(Sub& s) : sub_( s ) { }
Sub& sub_;
};
// for each type A, and for each type Sub having methods
// Sub::f(A& ) and Sub::g(A& ), map this to Wrap<A, Sub>
template <typename A, typename Sub>
Wrap<A, Sub>* wrap(Sub& sub)
{
return new Wrap<A, Sub>( sub );
}
// a subclass of Base<uint>, with the additional
// structure of having a method Subclass::g(uint& )
class Subclass : public Base<uint>
{
public:
virtual void f(uint& a) override { /*...*/ }
void g(uint& a) { /*...*/ }
};
int main()
{
Subclass sub;
Base<uint>* w = wrap( sub );
// ^ no matching function for call to ‘wrap(Subclass&)’
// template argument deduction/substitution failed:
// couldn't deduce template parameter ‘A’
uint a = 0;
w->f( a );
// ... delete w ...
return 0;
}
最佳答案
也许是这样的:
template <typename A>
class Base
{
public:
typedef A MyType;
virtual void f(A& ) = 0;
};
template <typename Sub>
Wrap<typename Sub::MyType, Sub>* wrap(Sub& sub)
{
return new Wrap<typename Sub::MyType, Sub>( sub );
}
关于c++ - 将具有特殊结构的子类映射到同一基类的另一个子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24662022/