将指针作为参数传递给模板

时间:2017-07-08 09:41:38

标签: c++

我有自己的数组类和数组比较规则草图

CArray.h

select getdistict(column1, column2) from table;

CArray.cpp

template <typename T>
    class CArray
    {
    public:

        CArray();
        virtual void setComparisonRule(IArrayComparisonRule<T>* comparisonRule);

    private:

        IArrayComparisonRule<T>* comparisonRule;    
    };

IArrayComparisonRule

template <typename T>
    void CArray<T>::setComparisonRule(IArrayComparisonRule<T>* comparisonRule)
    {
        this->comparisonRule = comparisonRule;
    }

数组元素

template <typename T>
    class IArrayComparisonRule
    {

    public:

        virtual b1 isLeftEqualRight(const T* leftItem, const T* rightItem) = 0;
        virtual b1 isLeftLessThenRight(const T* leftItem, const T* rightItem) = 0;
        virtual b1 isLeftGraterThenRight(const T* leftItem, const T* rightItem) = 0;
        virtual b1 isLeftLessOrEqualThenRight(const T* leftItem, const T* rightItem) = 0;
        virtual b1 isLeftGraterOrEqualThenRight(const T* leftItem, const T* rightItem) = 0;
    };

IArrayComparisonRule实现

class Sample
{
public:
    si32 value;

    Sample(si32 value = 0)
            : value{value}
    {}

    ~Sample()
    {}
};

的main.cpp

class SampleComparisonRule : public IArrayComparisonRule<Sample>
{

public:

    b1 isLeftEqualRight(const Sample* leftItem, const Sample* rightItem)
    {
        return leftItem->value == rightItem->value;
    }

    b1 isLeftLessThenRight(const Sample* leftItem, const Sample* rightItem)
    {
        return leftItem->value < rightItem->value;
    }

    b1 isLeftGraterThenRight(const Sample* leftItem, const Sample* rightItem)
    {
        return leftItem->value > rightItem->value;
    }

    b1 isLeftLessOrEqualThenRight(const Sample* leftItem, const Sample* rightItem)
    {
        return leftItem->value <= rightItem->value;
    }

    b1 isLeftGraterOrEqualThenRight(const Sample* leftItem, const Sample* rightItem)
    {
        return leftItem->value >= rightItem->value;
    }
};

如您所见,我使用T作为CArray和IArrayComparisonRule的模板。

编译器(GCC 5.4.0)错误没有匹配函数来调用'ee :: CArray :: setComparisonRule(SampleComparisonRule *)'

当我将Sample作为指向模板的指针传递时:

CArray<Sample*> objects;
objects.setComparisonRule(new SampleComparisonRule());

编译器说:'T'之前预期的嵌套名称说明符

从我的观点来看,如果我将Sample作为指针传递给IArrayComparisonRule,问题就可以解决了。我怎样才能做到这一点?也许还有另一种方法可以解决这个问题。

0 个答案:

没有答案