检查在模板第一个参数之后声明的函数是否为 NULL(传递向量和数组)

Check if function declared after Template first Argument is NULL (Passing Vector & Array)

本文关键字:NULL 向量 数组 是否 函数 第一个 参数 声明 之后 检查      更新时间:2023-10-16

在处理我的另一个项目时,我遇到了一个我认为是重载错误的问题。我打开了一个新项目,研究了重载,这里是快速代码:

#include <iostream>
#include <vector>
#include <string>
template<class T, class A>
void template_Function(T first_Arg, A second_Arg)
{
    if (first_Arg == NULL){
    std::cout << "First argument of the template function is null." << std::endl;
    std::cin.get();
    return;
}
int main()
{
    //Declare and assign values to vector.
    std::vector<std::string> my_Vector;
    my_Vector.push_back("Hello, Friend");
    //Declare and assign values (using for loop) to array.
    int my_Array[10];
    for (int i = 0; i < 10; i++)
    {
        my_Array[i] = i;
    }
    //Attempting to pass BOTH the vector and array to the template function.
    template_Function(my_Vector, my_Array);
    std::cin.get();
    return 0;
}

如果我运行这个,我得到错误代码C2678:二进制'=='等。我通过添加以下代码行解决了这个问题:

template<class T, class A>
void operator==(const T &q, const A &w);

就在我包含头文件之后。新的错误状态

error C2451: conditional expression of type 'void' is illegal c:usersaxiomdocumentsvisual studio 2013projects_test_template_test_templatesource.cpp 11 1 _test_Template

我认为这意味着,从所有的谷歌搜索,我不能比较"first_Arg"与NULL。这就是我要做的,看看first_Arg是否为空然后从那里开始。

感谢您的帮助

您正在传递值类型(向量)给函数,但随后尝试&将它与指针(NULL)进行比较。这行不通。

所以要么你声明你的函数接受一个参数T*,强迫你使用&my_Vector传递my_Vector,或者你切换到引用语义(const如果你喜欢),根本不与NULL比较。