C++嵌套模板类

C++ Nested Template Classes

本文关键字:嵌套 C++      更新时间:2023-10-16

如何使用"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();

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

"无效使用模板名称'A::B' 没有参数列表"在"B& foo((...">

"'A类'没有名为'foo'的成员">

我在关闭 B 类后编写了函数"foo",所以它可能是正确的......

您的代码存在三个问题:

  1. 缺少public访问说明符。foo()将无法在外部class A访问。
  2. 您还需要将模板参数添加到返回类型中,即将成员函数声明为B<T> foo()。更好的是,让编译器推断返回类型(适用于 C++14 及更高版本(,所以只需编写auto foo()
  3. 您正在返回对局部变量的引用,这会导致未定义的行为。只需将局部变量作为值返回,由于复制省略,您无需担心性能问题。

考虑到这一点,您的代码应该可以工作。