如何从模板类返回派生类型

How to return the derived type from a template class

本文关键字:返回 派生 类型      更新时间:2023-10-16

我希望能够调用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();
}