如何从模板类返回派生类型
How to return the derived type from a template class
我希望能够调用firstHalf()
而不提供模板参数。我试过在函数体内外使用不同形式的decltype(this)
,但没有成功。我很想看到c++ 14的解决方案。
#include <vector>
template <class T>
class A : public std::vector<T> {
public:
template <class Derived>
Derived firstHalf() {
Derived result;
for (auto it = begin(); it != begin() + size() / 2; ++it)
result.push_back(*it);
return result;
}
};
class B : public A<int>
{
/* stuff */
};
int main() {
B foo;
for (int i = 1; i <= 11; ++i)
foo.push_back(i);
B bar = foo.firstHalf(); // this doesn't work
B bar = foo.firstHalf<B>(); // (but this does)
}
看起来你想要一个奇怪的循环模板模式:
template <class T, class Derived>
class A {
public:
Derived makeAnother() {
Derived result;
// ...
return result;
}
private:
std::vector<T> v;
};
class B : public A<int, B> {};
int main() {
B foo;
B result = foo.makeAnother();
}
相关文章:
- 返回派生类型时出现协变类型错误
- C++ 基类调用但返回派生类
- typeid.name 返回派生类类型之前的数字
- 无法返回派生类型的标准::unique_ptr<>
- 如何在不转换回基类类型的情况下返回派生类型的对象?
- 从虚拟方法返回派生对象作为基础
- 不能返回派生的类(无法转换)
- 使用动态铸件来返回派生类内部的变量的不同值
- 如何返回派生类型
- 继承的函数返回派生类,而不是基类
- 从基类成员函数返回派生类的实例
- 如何重写 QObject::findChildren 以仅返回派生类型
- 从基类型的函数返回派生类对象
- 基类方法返回派生类 objec
- 重写虚拟方法时无法返回派生类指针
- 具有基类向量的类的下标运算符重载,该向量必须返回派生类
- 从指向基类型的指针向量,返回派生类型的第一个元素,该元素被强制转换为派生类型
- 返回派生类类型的基类中的方法
- 在基类和派生类上操作时如何返回派生类型
- 通过抽象基类的指针返回派生类对象