嵌套模板类的实例化

时间:2015-12-17 23:56:28

标签: c++ templates c++11 nested

我有一个如下所示的课程:

template <class T>
class outer {
public:
  typedef T TType;
  std::vector <TType> v;
  int f1 (TType t) {cout << "t= " << t << endl;};

  class inner {
  public:
    inner& operator=(const inner &in) {return *this;}
    void f2(const inner &in) {cout << "in f2\n";}    
  };
  inner read() {cout << "in read\n";return inner();}
};

外部必须嵌套inner。我必须为outer创建一个Base类(我们将在这里向后退!!)。我应该能够从基地派生outer1outer的现有客户应该在不改变任何内容的情况下工作。 outer应该只添加从基类派生的代码。

我的解决方案是:

template <typename T>
class outer_iface {
public:  
  typedef T TType;
  std::vector <TType> v;
  virtual int f1(TType t) {cout << "bt= " << t << endl;}; 

  template <typename U>
  class inner_iface {
  public:
    using value_type = U;
    inner_iface& operator=(const inner_iface &in)
    {
      return static_cast <U*> (this)->operator=(in);
    }
    void f2(const inner_iface &in)
    {
      return static_cast <U*> (this)->f2(in);
    }
  }; //inner_biface

  /*template <typename U>
  typename inner_iface <U>::value_type read()
  {
    return static_cast <U*> (this)->read();
  }*/
};

template <typename T>
class outer : public outer_iface  <T> {
public:
  typedef T TType;
  std::vector <TType> v;
  int f1 (TType t) {cout << "t= " << t << endl;};

  class inner : public outer_iface <T> :: template inner_iface <inner>  {
   public:
     inner& operator=(const inner &in) {return *this;}
     void f2(const inner &in) {cout << "in f2\n";}    
 };
 inner read() {cout << "in read\n";return inner();}
};

编译和构建。但是,我有两个问题:

  1. read中我outer_iface更正的声明/定义?
  2. 如何实例化outer_iface,说int类型,并致电read
  3. 我试过main()

    outer_iface<int> oi;
    oi.read();
    
  4. clang给出了错误:

    g++ -g --std=c++11 test7.cpp
    test7.cpp: In function ‘int main()’:
    test7.cpp:62:11: error: no matching function for call to       
    ‘outer_iface<int>::read()’oi.read();
                                      ^
    test7.cpp:62:11: note: candidate is:
    test7.cpp:28:40: note: template<class U> typename      
    outer_iface<T>::inner_iface<U>::value_type outer_iface<T>::read() 
    [with U = U; T = int]
    typename inner_iface <U>::value_type read()
                                    ^
    test7.cpp:28:40: note:   template argument deduction/substitution failed:
    test7.cpp:62:11: note:   couldn't deduce template parameter ‘U’
    oi.read();
    

    所以,显然我没有做对。我该如何解决inner_face::read? 任何帮助/见解表示赞赏。 谢谢 sdp

1 个答案:

答案 0 :(得分:0)

似乎你想要这样的东西:

template <typename T>
class outer_iface {
public:  
    // ...

    typename T::inner read()
    {
        // std::cout << "in read\n"; return typename T::inner();
        return static_cast<T*>(this)->read();
    }
};