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

cam*_*ous 1 c++

我希望能够在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)
}
Run Code Online (Sandbox Code Playgroud)

asc*_*ler 5

看起来你想要 Curiously Recurring Template Pattern:

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();
}
Run Code Online (Sandbox Code Playgroud)