试图使C++(MFC)代码片段易于重用.有什么选择

Trying to make a C++ (MFC) code snippet easy to reuse . What are the options?

本文关键字:易于重 片段 选择 什么 代码 C++ MFC      更新时间:2023-10-16

我发现自己反复编写以下函数:

// This function will try to find the 'item' in 'array'.
// If successful, it will return 'true' and set the 'index' appropriately.
// Otherwise it will return false.
bool CanFindItem(data_type item, const data_type* array, int array_size, int& index) const
{
    bool found = false;
    index=0;
    while(!found && i < array_size)
    {
         if (array[index] == item)
              found = true;
         else index++;             
    }
    return found;
}

通常我会为每个类/结构等需要它的地方编写一个类似的函数。

我的问题是,有没有一种方法可以让这个片段在不重写的情况下随时使用?我正在VS 2010中编程。

您可以将其移动到.h文件并将template<typename data_type>放在函数的前面,从而将其转换为模板。

您也可以切换到使用标准C++功能,例如std::find算法。

即使在MFC中,您也可以使用现代(即1995年后)c++和STL构造

您可以使用std::find。。。链接中有一个使用数组的示例。

(std::find (array,array + array_size, item) != array + array_size);