c++ - 从父模板中使用 child 的内部类

标签 c++ visual-studio templates

我有一个类 A,它派生自类模板 B。A 有一个 B 需要使用的内部类,如果不能,那么设计就没有意义了。

template <typename child_t>
class B {
    typename child_t::inner_t& some_func();
};

class A : public B<A> {
public:
    class inner_t { };
};

但是,当我尝试这样做时,编译器告诉我 A 没有名为 inner_t 的成员。我的第一个猜测是,这是因为 A 只是部分定义,但这种模式一直在使用。有办法解决这个问题吗?

最佳答案

有几种方法可以解决这个问题。

  1. 使 B 使得 A 不必派生自它。

    template <typename child_t>
    struct B1 {
    
        typedef typename child_t::inner_t inner_t;
    
        inner_t foo()
        {
           return inner_t();
        }
    };
    
    struct A1 
    {
       struct inner_t {};
    };
    

    然后,您可以像这样使用它:

    B1<A1> obj1;
    A1::inner_t inner = obj1.foo();
    
  2. 在进行函数调用之前不要指望 A 的定义。

    template <typename child_t>
    struct B2 {
    
        void foo()
        {
           typedef typename child_t::inner_t inner_t;
           // Do something with inner_t()
        }
    };
    
    struct A2 : public B2<A2>
    {
       struct inner_t {};
    };
    

    然后,您可以像这样使用它:

    B2<A2> obj2;
    obj2.foo();
    

关于c++ - 从父模板中使用 child 的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24153316/

相关文章:

C++ : Any possibility to declare a struct in main. cpp 但在 header 中有一个带有类的模板

C++ 模板类默认构造函数失败

c# - NuGet 缓存和版本控制问题

c# - CSC : error CS2001: Source file '.NETPortable,Version=v4.5,Profile=Profile78.AssemblyAttributes.cs' could not be found

c++ - 在 public、protected 和 private 之外声明的类成员函数

c++ - 使用 C header 时如何解决名称冲突?

database - Visual Studio 数据库项目约束 - 表脚本还是单独的文件?

c++ - 在 C++11 中使函数模板参数无符号

c++ - 在 C++ 中自动绑定(bind) boost::thread?

c++ - 能够实例化对象但不能访问其函数 - 'Symbol(s) not found' 错误