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

时间:2015-08-03 22:04:48

标签: 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)
}

1 个答案:

答案 0 :(得分:4)

看起来你想要好奇的重复模板模式:

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();
}