我正在构建一个简单的文本分析器。我有以下代码:
template<typename FwdIt0, typename FwdIt1, typename Comp, typename Num>
Num SmartAnalyzer::count_intersection(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1, Comp less, Num n)
{
while (beg0 != end0 && beg1 != end1)
{
if (less(*beg0, *beg1)) ++beg0;
else if (less(*beg1, *beg0)) ++beg1;
else
{
++n;
++beg0;
++beg1;
}
}
return n;
}
// Finds intersection between 2 sentences and divide it to the average sentence length
template<typename FwdIt0, typename FwdIt1>
double SmartAnalyzer::intersection_weight(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1)
{
double const mid_size = 0.5 * (std::distance(beg0, end0) + std::distance(beg1, end1));
/* LINE 38 */ double const intsc = count_intersection(beg0, end0, beg1, end1, std::less<>(), double());
return intsc / mid_size;
}
当我尝试编译它时,我得到了:
.. / lib / analyzer.cpp: In member function ‘double SmartAnalyzer::intersection_weight(FwdIt0, FwdIt0, FwdIt1, FwdIt1)’ :
.. / lib / analyzer.cpp : 38 : 76 : error : wrong number of template arguments(0, should be 1)
GCC 4.7 on Debian
。我认为这与GCC有某种联系,直到4.7+不支持模板别名,但我不知道如何解决它。我没有机会将gcc更新为4.8。
答案 0 :(得分:1)
std::less
类型。但它不适用于异构类型(它将在C ++ 14中)。因此,在您的情况下,value_type
和FwdIt0
不能有不同的FWdIt1
。
也许您可以尝试以下方法(当上述问题得到解决时):
template<typename FwdIt0, typename FwdIt1>
double SmartAnalyzer::intersection_weight(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1)
{
typedef std::iterator_traits<FwdIt0>::value_type less_type;
double const mid_size = 0.5 * (std::distance(beg0, end0) + std::distance(beg1, end1));
/* LINE 38 */ double const intsc = count_intersection(beg0, end0, beg1, end1, std::less<less_type>(), double());
return intsc / mid_size;
}
答案 1 :(得分:1)
这个适合我(gcc 4.8)
正如我在评论中指出的那样,问题在于您错过了std::less
的模板参数(请注意,似乎在C ++ 14上的内容较少得到specialization for void parameter)
我添加了一个新模板参数X
#include <functional>
#include <iterator>
#include <vector>
template<typename FwdIt0, typename FwdIt1, typename Comp, typename Num>
Num count_intersection(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1, Comp less, Num n)
{
while (beg0 != end0 && beg1 != end1)
{
if (less(*beg0, *beg1)) ++beg0;
else if (less(*beg1, *beg0)) ++beg1;
else
{
++n;
++beg0;
++beg1;
}
}
return n;
}
// Finds intersection between 2 sentences and divide it to the average sentence length
template<typename FwdIt0, typename FwdIt1,typename X>
double intersection_weight(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1)
{
double const mid_size = 0.5 * (std::distance(beg0, end0) + std::distance(beg1, end1));
/* LINE 38 */ double const intsc = count_intersection(beg0, end0, beg1, end1, std::less<X>(), double());
return intsc / mid_size;
}
int main() {
std::vector<int> a;
std::vector<int> b;
intersection_weight<std::vector<int>::iterator,std::vector<int>::iterator,int>(a.begin(),a.end(),b.begin(),b.end());
}