【发布时间】:2021-10-01 19:41:35
【问题描述】:
我尝试使用如下模板引发堆栈溢出:
#include <iostream>
using namespace std;
#define endl '\n'
template <class T>
// void next (T a) cout << a++ << endl; // can't write in a line without {}
void next (T a)
{
if (typeid(a) == typeid((char) 'a') || typeid(a) == typeid((unsigned char) 'a'))
{
cout << typeid(a).name() << " : " << (int) a << " + 1 = " << (int) ++a << " (converted to ASCII value)" << endl;
} else
{
cout << typeid(a).name() << " : " << a << " + 1 = " << ++a << endl;
}
// there will be more alternatives like type_info and so on ……
}
int main()
{
next((char) CHAR_MAX);
next((unsigned char) UCHAR_MAX);
next((short) SHRT_MAX);
next((unsigned short) USHRT_MAX);
next((int) INT_MAX);
next((unsigned int) UINT_MAX);
next((bool) 1); // warning: use of an operand of type 'bool' in 'operator++' is deprecated
return 0;
}
- 结果:
c : 127 + 1 = -128 (converted to ASCII value)
h : 255 + 1 = 0 (converted to ASCII value)
s : 32767 + 1 = -32768
t : 65535 + 1 = 0
i : 2147483647 + 1 = -2147483648
j : 4294967295 + 1 = 0
b : 1 + 1 = 1
这是我之前的高级代码,它为每种数据类型重载了类似的函数(太遗憾了,所以应该保密)。
但是现在我有更多的问题,我是否可以在main() 中压缩next() 的系列更多。我认为它似乎需要一个可以包含各种类型数据的容器;例如,{short 1, int 10, long long 100}。
感谢您的建议,最重要的是,请注意您的健康。
【问题讨论】:
-
您似乎以错误的方式学习 C++。您的术语似乎错误且令人困惑。这个问题非常不清楚。我不知道你在问什么。
-
好吧,我的意思是找到一些比重复使用
next()更有效的方法。所以我想,如果有一个容器可以有各种类型的元素,我可以很容易地在for循环中替换它。 -
如果我没看错的话,听起来你想要一个
std::tuple,然后使用this 为元组的每个元素调用一个函数。
标签: c++ types stl containers