Inside a member function of a template class, I need a compare that works for int, float and string. My solution is to let the member function (DFA::entry) use a selfmade comp function:(template < class T, class U> int comp(T s_one, U s_two)).
The problem now is that after compiling, when the programm starts. I get a exception thrown for a access violation when trying to write at a position 0x00000004.
I only put in the parts of my code that I think are relevant for the problem, because without the comp function the programm works perfectly fine (but just for int).
Is this the right way to let a template member function use a non-member template function?
#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;
}
First of all: That's not a valid comparison function for floats, because it's not a partial order (in particular, it doesn't satisfy transitivity: you can have a, b, and c such that a compares equivalent to b and b compares equivalent to c, but a doesn't compare equivalent to c.) You cannot use your comparison with things like std::map
or std::sort
or std::binary_search
.
Secondly, you're comparing s_two
against s_two
, when I think you meant to compare it against s_one
. So that's gonna cause problems too.
Again, though, this comparison is already fatally flawed. A valid comparison for floats is a < b
. Mucking about with "epsilons" is the wrong solution to whatever problem you're trying to solve with them.
User contributions licensed under CC BY-SA 3.0