c++ - 如何从模板类返回派生类型

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

最佳答案

看起来你想要 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();
}

关于c++ - 如何从模板类返回派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31797546/

相关文章:

c++ - 带有 C++ 错误 : undefined reference to mysql_init 的 Mysql

c++ - 我可以将空指针传递给 memcmp 吗?

c++ - 二叉树为了toString函数C++

c++ - 确定运行时参数的性质

c++ - 回溯时如何避免输出参数?

c++ - 如何确保两个不同的 vector 在 C++ 中以相同的顺序混洗?

C++ 二项式系数太慢

c++ - 如何为无序映射 C++14 包含更好的位混合器

c++ - 是否可以使用 QMaemo5ListPickSelector 将图像显示为项目?

c++ - 我的 min 方法(二叉搜索树)有什么问题?