下面这段小代码需要您的专家帮助:
template<typename T> void print_element(T t)
{
int width;
if(pre_def_const+2 < 8) width=8;
else width = pre_def_const+2;
cout << left << setw(width) << setfill(' ') << t;
}
此函数将仅接收 double 和字符串参数,我希望能够区分每种情况。
简而言之,我想在上面的代码中添加类似这样的内容:
if(T==double) ...
if(T==string) ...
我需要这个来测试 double 是否小于零。 谢谢!
最佳答案
This function will receive only doubles and string parameters
那么应该不是模板。而是创建两个重载函数:
void print_element(double d);
void print_element(std::string const& s);
从技术上讲,是一种非常接近您所需语法的语言结构:typeid
。这根本不是一个好的解决方案,所以为了完整起见,我将发布一个示例,而不是因为我建议您在实际代码中这样做:
#include <iostream>
#include <typeinfo>
#include <iomanip>
#include <string>
int pre_def_const = 10;
int left = 20;
template<typename T> void print_element(T t)
{
if (typeid(t) == typeid(double))
{
std::cout << "double instantiation of template called\n";
}
int width;
if(pre_def_const+2 < 8) width=8;
else width = pre_def_const+2;
std::cout << left << std::setw(width) << std::setfill(' ') << t;
}
int main()
{
print_element(1.0);
std::cout << "\n";
print_element("x");
}
关于c++ - 在运行时识别模板类型名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29051199/