1

我有以下比较函数,我将其传递给std::sort算法以对对象向量进行排序:

template <typename PointT>
bool myCompareLines (A<PointT>::model_struct model_a, A<PointT>::model_struct model_b) {
    return (/* some comparison code*/);
}

比较函数在类外部声明,我这样称呼它:

template <typename PointT>
class B {
    [...]
    std::sort(lines.begin().lines.end(),::myCompareLines);
    [...]
}

当我编译我得到错误:template declaration of 'bool myCompareLines'

在里面class A我声明class B为一个朋友类,以便class B可以访问私有类型model_struct。我错过了什么?

4

4 回答 4

2

虽然丑陋,但这就是你要找的吗?注意:编译不等于好。即使这对您有用,我也会建议另一种声明层次结构的方法。

template<class PointT>
class A
{
public:
    A() {};

    struct model_stuct
    {
        // need something to use in comparison, so i just threw this in.
        int value;
    };
};

// comparitor
template<class PointT>
bool compareLines(
    const typename A<PointT>::model_stuct& left,
    const typename A<PointT>::model_stuct& right)
{
    return left.value < right.value;
}

template<class PointT>
class B
{
public:
    B() : lines() {};

    void sort()
    {
        std::sort(lines.begin(), lines.end(), compareLines<PointT>);
    }

    std::vector<typename A<PointT>::model_stuct> lines;
};


// main entrypoint
int main(int argc, char *argv[])
{
    // this does nothing, but demonstrate that it can compile and
    //  sort() doesn't puke. 
    B<int> bInt;
    bInt.sort();
    return 0;
}
于 2012-10-15T00:09:01.057 回答
1

我的 CompareLines 签名中缺少 typename 关键字。

这修复了它:

bool myCompareLines (typename A<PointT>::model_struct model_a, typename B<PointT>::model_struct model_b)
于 2012-10-15T01:51:04.740 回答
1

你不应该这样做:

template <typename PointT>
class B {
    [...]
    std::sort(lines.begin(), lines.end(), ::myCompareLines<PointT>);
    [...]
}
于 2012-10-14T23:52:27.740 回答
0

编译器无法PointT从内部类推导出模板参数A<PointT>::model_struct

它不能因为许多专业化A<PointT>可以具有相同的model_struct- 比如:

template <class PointT>
class A {
public:
  typedef int model_struct;
};

用这个例子:

   int a;
   bool res = compareLines(a,a);

定义model_struct为顶级模板。

于 2012-10-14T23:50:31.553 回答