模板函数传递参数的 Typeid() 检查

Typeid() Check of Passing Paramaters of A Templated Function

我不想对函数中的小改动使用函数重载。相反,我想使用 typeid() 检查下面模板化函数的传递参数。但是,如果我不注释掉下面代码中的行,它会给出编译错误:

Severity    Code    Description Project File    Line    Suppression State
Error       invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >')

据我所知,编译器不知道该怎么做。有解决办法吗?

密码是:

#include <iostream>
#include <vector>

using namespace std;


template <class T>
void Test(T A)
{
    if (typeid(T) == typeid(vector<string>)) {
        cout << "The type of A is vector<string>" << endl << endl;
        //cout << "First element of A is:" << A[0] << endl;    // If I don't comment out this line, it gives the compiler error.
    }

    if (typeid(T) == typeid(vector<vector<string>>)) {
        cout << "The type of A is vector<vector<string>>" << endl;
        cout << "First row first element of A is:" << A[0][0] << endl;
    }
}

int main()
{
    Test(vector<string> {"1", "2", "3"});

    Test(vector<vector<string>> { {"11", "12", "13"}, { "21", "22", "23" }});

    return 0;
}

问题出在普通ifstatement-true(和statement-false 如果存在)在编译时必须是有效的语句,无论 条件 的结果是什么,对于类型为 Test 的每个实例=13=]给出。

从 C++17 开始您可以使用 constexpr if(使用 std::is_same)。

In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool. If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.

例如

if constexpr (std::is_same_v<T, vector<string>>) {
    cout << "The type of A is vector<string>" << endl << endl;
    cout << "First element of A is:" << A[0] << endl;
} 

if constexpr (std::is_same_v<T, vector<vector<string>>>) {
    cout << "The type of A is vector<vector<string>>" << endl;
    cout << "First row first element of A is:" << A[0][0] << endl;
}

LIVE

在 C++17 之前,您可以使用 SFINAE or specialization (with templates), or just overloading(即使没有模板)。