c++ - 将具有特殊结构的子类映射到同一基类的另一个子类

标签 c++ templates inheritance c++11 types

在 C++ 中,我有一个基类参数化超过 1 种类型,对于每个具有特定附加结构的子类,我想将该子类映射到另一种类型,这也是同一基类的子类。然而,我的代码产生了一个错误,编译器不会按照我的意图去做。所以

  1. 我应该如何修复我的代码以获得 int main()工作?
  2. 模板功能可以吗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/

相关文章:

c++ - 将单个字符 QString 转换为 Char

c++ - MFC 主 UI 线程工作和模式对话框

C++ 类成员的循环引用

c++ - 在调整大小时禁用 vector 填充值? C++

c++ - 使用类模板的部分特化

java - 使用Selenium Webdriver和Cucumber继承Java中的xpath字符串

java - 为什么将变量和对象声明为不同的类型?

c++ - 如何使用父类的操作符?

python - 如何在 Flask 的页面上显示小部件?

c++ - 如何在编译时验证模板类是从给定类派生的?