【问题标题】:Template function that can take another function to check how many elements meets the condition模板函数,可以带另一个函数来检查有多少元素满足条件
【发布时间】:2019-07-06 06:51:41
【问题描述】:

我有一个函数模板,它需要另一个函数(类)模板来检查特定条件。 这一切都适用于 int 或 doubles,但是当我想让它适用于我的分数时,我不知道该怎么做。

template <class T, class F>
int HowManyF( int count, T *array, F function )
{
    int howmany = 0;

    for (int i = 0; i < count; i++)
    {
    if ( function(array[i]) )
        howmany++;
    }
    return howmany;
}

template <class T>
class NotNegative
{
    public:
        T operator()(T arg);
};

template <class T>
T NotNegative<T>::operator()(T arg)
{
    if (arg<0) return 0;
    else return 1;
}

class Fraction{
public:
    int numerator;
    int denominator;

    Fraction() {};
    Fraction(int nume, int denom = 1);
    Fraction operator += (const Fraction &u);
};

// this works
int ints[8]  = {1,2,3,4,-5,6,-12,16};
howmany = HowManyF(8,ints,NotNegative());
cout << "NonNegative (ints) " << howmany << endl;

// this not - conditional expression of type 'Fraction' is illegal
// shows in line    if ( function(array[i]) )
Fraction *tab = new Fraction[2];
    tab[0] = Fraction(2, 4);
    tab[1] = Fraction(5, 6);

howmany = HowManyF(2,tab,NotNegative<Fraction>());
cout << "NonNegative (fractions) " << howmany << endl;

我该怎么办?我需要将类模板更改为功能模板吗?我需要在 Fraction 类中添加一些运算符吗?我需要改变一种方法来检查变量是否为

【问题讨论】:

  • “我该怎么办?” 给我们编译器错误verbatim ;)
  • “我有函数模板什么需要另一个函数(类)模板”注意术语,模板参数可以是模板本身(模板模板参数),但你的模板参数都是类型,不是模板
  • 看看NotNegative 做了什么(arg&lt;0)。 Fraction 是否支持该操作?
  • 另外,您的HowManyF 恰好是std::count_if 的穷人版本。如果你把它写成学习材料,那很好,如果不是:知道并使用你的&lt;algorithm&gt;。
  • 你的 NotNegative&lt;T&gt;::operator()(T arg) 应该返回 bool 顺便说一句,谓词 (NotNegative) 最好用一个简单的 lambda 替换。

标签: c++ templates fractions negative-number


【解决方案1】:

你的谓词错了,尤其是返回类型,应该是:

template <class T>
class NotNegative
{
public:
    bool operator()(T arg) const { return !(arg < 0); }
};

那么您可能需要对Fraction 进行专门化,或者在Fraction 和int 之间实现operator &lt;。

【讨论】:

    猜你喜欢
    • 2012-12-04
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2013-03-06
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多