C++嵌套模板类
C++ Nested Template Classes
如何使用"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
和
"'A类'没有名为'foo'的成员">
我在关闭 B 类后编写了函数"foo",所以它可能是正确的......
您的代码存在三个问题:
- 缺少
public
访问说明符。foo()
将无法在外部class A
访问。 - 您还需要将模板参数添加到返回类型中,即将成员函数声明为
B<T> foo()
。更好的是,让编译器推断返回类型(适用于 C++14 及更高版本(,所以只需编写auto foo()
- 您正在返回对局部变量的引用,这会导致未定义的行为。只需将局部变量作为值返回,由于复制省略,您无需担心性能问题。
考虑到这一点,您的代码应该可以工作。
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray