重载模板功能



在模板类的成员函数中,我需要一个适用于int、float和string的比较。我的解决方案是让成员函数(DFA::entry(使用自制的comp函数:(template<class T,class U>int comp(T s_one,U s_two((。

现在的问题是,在编译之后,当程序启动时。尝试在0x00000004位置写入时,由于访问冲突而引发异常。

我只放入了我认为与问题相关的代码部分,因为没有comp函数,程序运行得很好(但仅适用于int(。

这是让模板成员函数使用非成员模板函数的正确方法吗?

#define EPSILON 0.9
//Forward and non-member-Function Declarations
template< class dto_s, class dto_ea, int nQ, int nSigma, int nF > class DFA;
template <class T, class U>
int comp(T s_one, U s_two) {
int ret_val = 0;
if (s_two > s_two)
{
ret_val = ((s_two - s_one) < EPSILON);
}
if (s_one > s_two)
{
ret_val = ((s_one - s_two) < EPSILON);
}
return ret_val;
}
inline int comp(std::string s_one, std::string s_two) {
//return abs(s_one.compare(s_two));
return (s_one == s_two);
}

//Class Definition
template< class dto_s, class dto_ea, int nQ, int nSigma, int nF > class DFA
{
public:
int entry(dto_ea[]);
//Returns index of entry in Sigma
int entry_to_number(dto_ea);
//Returns index of state in Q
int state_to_number(dto_s);
private:
std::array<dto_s, nQ> Q;
std::array<dto_ea, nSigma> Sigma;
std::array<dto_s, nQ * nSigma> Delta;
std::array<dto_s, nF> F;
dto_s* current_state;
};

//              ENTRY FUNCTION
template<class dto_s, class dto_ea, int nQ, int nSigma, int nF>
inline int DFA<dto_s, dto_ea, nQ, nSigma, nF>::entry(dto_ea wort[])
{
dto_s* temp_state = current_state;
//these 2 functions work correctly and return a int
row = state_to_number(*temp_state);
column = entry_to_number(wort[i]);

for (auto i = Q.begin(); i != Q.end(); i++)
{
if (comp<dto_s, dto_s>(Delta[row * nSigma, column], (*i))) {
//do something
}
}
for (auto i = F.begin(); i != F.end(); i++)
{
if (comp<dto_s, dto_s>((*temp_state), (*i))) {
//do something
}
}

return return_code;
}

首先:这不是一个有效的浮点比较函数,因为它不是偏序(特别是,它不满足传递性:你可以有a、b和c,这样a比较等价于b,b比较等价于c,但a比较不等价于c。(你不能将比较用于std::mapstd::sortstd::binary_search之类的东西。

第二,你将s_twos_two进行比较,而我认为你的意思是将其与s_one进行比较。所以这也会带来问题。

然而,这种比较已经存在致命的缺陷。浮点值的有效比较是a < b。对于你试图用"epsilons"解决的任何问题,到处乱搞都是错误的解决方案。

最新更新