c++ - 如何将多种数据类型接受到我的输入流中?

标签 c++ templates

template< typename T >
void somefunction()
{
   T value;
   cout << " value = ";
   cin >> value;
}

现在这看起来有点奇怪,但我们可以有一个接受多个函数的模板吗? 数据类型(比如 float 和 int)。

最佳答案

如果你想将模板限制为 int 和 float,你必须专门化你的模板:

template< typename T >
void somefunction()
{
   // May be throw std::bad_typeid
};

template<>
void somefunction<int>()
{
   int value;
   cout << " int value = ";
   cin >> value;
};

template<>
void somefunction<float>()
{
   float value;
   cout << " float value = ";
   cin >> value;
};

关于c++ - 如何将多种数据类型接受到我的输入流中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5880345/

相关文章:

html - 直接从 django-template 发送电子邮件

c++ - 是否有 BOOST_FOREACH 的免 boost 版本?

c++ - constexpr 中的字节顺序

c++ - MFC CListCtrl 拖拽文件到Windows资源管理器

c++ - 如何从父模板函数访问子成员?

c++ - 实现可变最小值/最大值函数

C++ 模板样式,旨在更容易理解编译器错误消息

c++ - 使用 boost 查找数据集的峰度

c++ - 在 C++ 中转发声明一个类的 public typedef

c++ - SFINAE 给出 "Inheriting constructor does not inherit ellipsis"警告