【发布时间】:2019-11-14 11:09:04
【问题描述】:
在模板类的成员函数中,我需要一个适用于 int、float 和 string 的比较。我的解决方案是让成员函数(DFA::entry)使用自制的comp函数:(template 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;
}
【问题讨论】:
-
使用调试器来捕捉崩溃并在代码中找到它发生的位置。