【问题标题】:Overload template function重载模板函数
【发布时间】: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;
}

【问题讨论】:

  • 使用调试器来捕捉崩溃并在代码中找到它发生的位置。

标签: c++ templates


【解决方案1】:

首先:对于浮点数来说,这不是一个有效的比较函数,因为它不是偏序(特别是,它不满足传递性:你可以有 a、b 和 c,使得 a 与 b 等价比较b 与 c 等价比较,但 a 不与 c 等价比较。)您不能将您的比较与 std::map 或 std::sort 或 std::binary_search 之类的东西进行比较。

其次,您将s_two 与s_two 进行比较,而我认为您打算将其与s_one 进行比较。所以这也会引起问题。

同样,这种比较已经存在致命缺陷。浮点数的有效比较是a &lt; b。用“epsilons”来解决你试图用它们解决的任何问题都是错误的解决方案。

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多