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

C++ Typeid()检查模板化函数的传递参数,c++,windows,templates,typeid,C++,Windows,Templates,Typeid,我不想使用函数重载对函数进行小的更改。相反,我想使用typeid()检查下面模板化函数的传递参数。但是,如果我没有注释掉下面代码中的行,则会产生编译错误: Severity Code Description Project File Line Suppression State Error invalid operands to binary expression ('basic_ostream<char, std::char_traits<cha

我不想使用函数重载对函数进行小的更改。相反,我想使用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> > > >')
严重性代码描述项目文件行抑制状态
错误二进制表达式的无效操作数('basic_ostream'和'std::vector')
据我所知,编译器不知道如何操作。有解决办法吗

代码是:

#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;
}
#包括
#包括
使用名称空间std;
模板
孔隙试验(TA)
{
if(typeid(T)=typeid(向量)){
cout问题在于,对于给定类型的
T
Test
的每个实例化,在编译时,无论条件的结果如何,语句true(如果存在,则语句false)必须是有效的语句

您可以使用C++17(使用
std::is_same

在constexpr if语句中,条件的值必须是 .如果 如果
true
,则放弃语句false(如果存在),否则, 语句true被丢弃

e、 g

如果constexpr(std::is_same_v){
库特
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;
}