C ++正确返回类型的泛型集合的方法

时间:2012-02-25 01:30:46

标签: c++ algorithm templates generics containers

我是C ++的新手,不幸的是我无法停止用C#(我以前的语言)思考。 我读过一些书籍,论坛和C ++参考网站,但是我找不到我的问题的答案,所以我想在放弃和写一些丑陋的东西之前我也可以尝试一下。

好的,我们可以开始了。 我有一个带有抽象方法 succeorsFunction 的类,我希望它返回一个指向 State 的指针集合。我不想强制实现者到特定的容器;我宁愿让他们选择(矢量,列表等)。

所以它看起来像这样:

class Problem
{
public:
    virtual list<const State*>::iterator succesorsFunction(const State &state, list<const State*>::iterator result) const = 0;
};

这里的问题是列表的明确使用。你是如何用C ++做的?

我考虑过使用模板,但后来遇到了两个问题: 1)看起来你不能用抽象方法做到(或者我错了吗?) 2)如何告诉模板它应该包含指向State的指针?

4 个答案:

答案 0 :(得分:2)

您不能基于C ++中的返回类型重载方法。

此外,&#34;容器&#34;在C ++中没有相同的基础(如Java中的Collection),因此您无法返回通用容器。

我担心没有干净的方法可以做到这一点。

我只会写入重载(通过参数)或不同的函数名称。

对于你的问题:

1)你可以。是什么让你认为你不能?

2)与宣布list的方式相同:list<const State*> - const是可选的。

答案 1 :(得分:0)

您不能拥有虚拟的成员函数模板,但您可以尝试实现这样的朋友通用函数:

template <typename yourType>
yourType& succesorsFunction(const State &a, yourType &result){//Your return type can be without reference
    //Your body
    return result;
}

如果您使用vector<State> a参数调用您的函数,例如:

sucessorsFunction(b,a);// b is your State object

扣除流程会自动断定yourType实际上是vector<State>类型,我认为这可以解决您的问题。此外,这个架构还可以让您创建新的类类型MyVector(它包含States的数组)并将MyVector对象传递给succesorsFunction

答案 2 :(得分:0)

如果您确实要强制使用STL容器,请尝试以下操作:

template <template <typename, 
                    typename = std::allocator<const State *> > class Container>
 Container<const State*> successorsFunction(const State &state, const Container<const State*> &c) const
 {
    // return something useful.
 }

如果你坚持让这个函数成为虚函数,那么它就不能成为一个成员函数模板,只需要用你想要支持的类型重载它,然后就可以使它们虚拟化。

答案 3 :(得分:0)

这只是对C.T's答案的详细阐述。请记住,如果您返回指针容器,则必须明确释放它们或使用std::unique_ptr 只是一个FYI ..因为你来自C#背景。

您也可以使用State或将其模板化。

template<typename Type, 
         template< typename, typename = std::allocator<Type*> > class Container 
        >
Container<Type*> Successor(const Type& x)
{
    Container<Type*> cont;
    // something.
    cont.push_back(new Type(x));
    return cont;   
}

并将其命名为

vector<State*> states = Successor<State, vector>(State(10));
相关问题