C ++嵌套模板类

时间:2018-05-29 13:52:20

标签: c++ class templates nested

如何使用“A”类的方法返回“B”类型?例如:

template <typename T> class A{

    //something

        template <typename V> class B{

        //something

        };

    B& foo(){
        B<T> y; //the variable must have the same type T of the father class (for my exercise)
        //something
        return y;
    }
};

主:

A <int> o;
o.foo();

一旦我尝试编译它,它就会给我这些错误:

“在B&amp; foo()...”无效使用模板名'A&lt; T&gt; :: B',没有参数列表“

“'A级'没有名为'foo'的成员”

关闭B级后我写了函数“foo”,所以它可能是正确的......

1 个答案:

答案 0 :(得分:2)

您的代码有三个问题:

  1. 缺少public访问说明符。 foo()无法在class A之外访问{/ 1}}。
  2. 您还需要将模板参数添加到返回类型,即将成员函数声明为B<T> foo()。更好的是,让编译器推导出返回类型(适用于C ++ 14及更高版本),所以只需编写auto foo()
  3. 您正在返回对局部变量的引用,这会导致未定义的行为。只需将本地变量作为值返回,因为copy elision您不必担心性能问题。
  4. 考虑到这一点,您的代码应该有效。

相关问题