首页 > 解决方案 > 如何在 C++ 中将指针数组传递给函数模板

问题描述

我有一个模板类,在里面我有operator>应该从另一个文件调用模板函数的函数。如何设置函数参数或如何将参数传递给该函数。

我已经从 lambda 函数和 cmpFn 中删除了代码,因为这与本示例无关。

这是我的模板类,其中operator<调用了函数cmpFn。注意:在这个问题的先前版本中,我错误地声明了cmpFn.

#include "assert.h"

template <typename T>
class myvectest
{
public:
    T *arr;
    unsigned capacity;
    unsigned current;
    myvectest()
    {
        capacity = 1;
        arr      = new T[capacity];
        current  = 0;
    }
    unsigned size() const
    {
        return current;
    }
    bool operator<(const myvectest &toCompare) const
    {
        auto mfn = [ ](auto left, auto right) -> int { return 0 };
        return cmpFn(this->arr, toCompare.arr, this->size(), toCompare.size(), mfn);
    }
}

这是cmpFn,我在其中更新了参数 *a 和 *b

template <typename T>
bool cmpFn(T *a, T *b, unsigned size1, unsigned size2, int (*fnEq)(T, T))
{
    return false;
}

错误消息告诉我,即使有候选人,也没有匹配的函数调用。

.../myvectest.h:83:21: error: no matching function for call to ‘cmpFn(unsigned int* const&, unsigned int* const&, myvectest <T>::operator<(const myvectest<T>&) const [with T = unsigned int]::<lambda(auto:1, auto:2)>)’
   83 |         return cmpFn(
      |                ~~~~~^
   84 |                 this->arr,
      |                 ~~~~~~~~~~
   85 |                 toCompare.arr,
      |                 ~~~~~~~~~~~~~~
   86 |                 [ ](auto left, auto right) -> int { return 0; }
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   87 |         );
      |         ~ 

我知道,可能还有其他解决方案,但我想了解这种传递数组的方式应该如何工作。

提前致谢, 乌尔夫

编辑:请注意,这myvectest->arr是来自动态大小。由于这是某种重建std::vector类,所以还有一个 push_back 方法,可以改变类的大小和容量*arr

标签: c++arraysfunctionpointerstemplates

解决方案


你需要像这样声明你的比较函数:

template <typename T>
bool cmpFn(T *a, T *b, int (*fnEq)(std::type_identity_t<T>, std::type_identity_t<T>))
{
    return false;
}

但是std::type_identity_t是 C++20,对于以前的版本,你需要这样的东西:

template< class T >
struct type_identity {
    using type = T;
};
template< class T >
using type_identity_t = typename type_identity<T>::type;

此外,我已经从参数中删除了数组大小ab. 您不能在静态编译时推断出动态大小。如果你需要一个编译时间大小,你可以这样做:

template <typename T, size_t SZ1, size_t SZ2>
bool cmpFn(T (&a)[SZ1], T (&b)[SZ2], int (*fnEq)(std::type_identity_t<T>, std::type_identity_t<T>))
{
    return false;
}

template <typename T, size_t SZ>
class myvectest
{
public:
    T arr[SZ];
    size_t capacity = SZ;
    size_t current;

    myvectest() = default;

    size_t size() const
    {
        return current;
    }

    bool operator<(const myvectest &toCompare) const
    {
        return cmpFn(
                this->arr,
                toCompare.arr,
                [](auto left, auto right) -> int { return 0; }
        );
    }
};

推荐阅读