gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:03:57 30 4
gpt4 key购买 nike

我不想使用函数重载来对函数进行小的更改。相反,我想使用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;
}

最佳答案

问题出在普通的if中,对于条件为给定的Test类型的T的每个实例化,无论条件是什么结果,语句true(如果存在则为false)都必须是有效的语句。

自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之前,您可以使用 SFINAEspecialization(带有模板),或者仅使用 overloading(甚至不带模板)。

关于c++ - Typeid()检查模板化函数的传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61172195/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com