c++ - 限制模板功能

标签 c++ templates

我在 http://codepad.org/ko8vVCDF 写了一个示例程序使用模板函数。

如何将模板函数限制为仅使用数字? (int、double 等)

#include <vector>
#include <iostream>

using namespace std;

    template <typename T>
T sum(vector<T>& a)
{
    T result = 0;
    int size = a.size();
    for(int i = 0; i < size; i++)
    {
        result += a[i];
    }

    return result;
}

int main()
{
    vector<int> int_values;
    int_values.push_back(2);
    int_values.push_back(3);
    cout << "Integer: " << sum(int_values) << endl;

    vector<double> double_values;
    double_values.push_back(1.5);
    double_values.push_back(2.1);
    cout << "Double: " << sum(double_values);

    return 0;
}

最佳答案

这可以通过使用 SFINAE , 并通过使用来自 Boost 或 C++11 的帮助器变得更容易

提升:

#include <vector>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_arithmetic.hpp>

template<typename T> 
    typename boost::enable_if<typename boost::is_arithmetic<T>::type, T>::type 
        sum(const std::vector<T>& vec)
{
  typedef typename std::vector<T>::size_type size_type;
  T result;
  size_type size = vec.size();
  for(size_type i = 0; i < size; i++)
  {
    result += vec[i];
  }

  return result;
}

C++11:

#include <vector>
#include <type_traits>

template<typename T> 
    typename std::enable_if<std::is_arithmetic<T>::value, T>::type 
        sum(const std::vector<T>& vec)
{
  T result;
  for (auto item : vec)
    result += item;
  return result;
}

关于c++ - 限制模板功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/148373/

相关文章:

c++ - 虚函数调用优化

c++ - 是什么导致了模板和继承中出现这种令人困惑的编译器错误?

c++ - 将指向模板函数的指针作为函数参数传递?

c++ - 请求从 `double' 到非标量类型的转换和一些其他错误

java - 编辑 "Test for Existing Class"的 Netbeans 模板

c++ - 如何根据模板类型定义浮点常量?

angularjs - Angular : difference when using template or templateUrl

c++ - 未定义 对 "_ZNSt5__padIcSt11char_traitsIcEE6_S_padERSt8ios_basecPcPKcllb"符号的引用未从 libstdc++.a(libstdc++.so.6) 导出

C++、mingw 和 clock_gettime 无法编译

c++ - 传递参数时的宏扩展问题