一个接受std :: vector和QVector的函数模板?

时间:2018-05-08 10:39:07

标签: c++ templates vector c++17 qvector

假设我有一个名为loadData()的函数,它接受一个容器(用数据填充)和一个CSV文件。我需要以下重载:

  1. loadData(std::vector<double>& data, const std::string& file);
  2. loadData(QVector<double>& data, const std::string& file);
  3. loadData(std::vector<std::complex<double>>& data, const std::string& file);
  4. loadData(QVector<std::complex<double>>& data, const std::string& file);
  5. loadData(std::vector<std::vector<double>>& data, const std::string& file);
  6. loadData(QVector<QVector<double>>& data, const std::string& file);
  7. loadData(std::vector<std::vector<std::complex<double>>>& data, const std::string& file);
  8. loadData(QVector<QVector<std::complex<double>>>& data, const std::string& file);
  9. QVector是Qt类似矢量的类,具有类似的API,但只采用一个模板参数T(而不是两个,如std::vector<T, A>)。

    1-4的实现几乎相同(它只调用5-8,将该单个向量包装在另一个向量中(相同类型!)。

    5-8的实现是相同的(它只是调用CSV解析函数的适当重载)。

    我可能还需要添加float重载或QVector<std::vector<...>> / std::vector<QVector<...>>重载。

    基本上,这是我想要概括的一大堆重载。

    是否可以将它们全部组合成2个功能模板(一个用于1D容器,另一个用于2D容器)?

    由于

3 个答案:

答案 0 :(得分:3)

  

是否可以将它们全部组合成2个功能模板(一个用于1D容器,另一个用于2D容器)?

是的......需要一点工作,但相对简单。

也许有更简单的方法,但我建议创建一个自定义类型特征,以验证模板模板是std::vector还是QVector

template <template <typename...> class>
struct isVector : public std::false_type
 { };

template <>
struct isVector<std::vector> : public std::true_type
 { };

template <>
struct isVector<QVector> : public std::true_type
 { };

接下来是另一个自定义类型特征,用于验证类型是否为std::complex<T>类型的浮点类型

template <typename T>
struct isCFloating : public std::is_floating_point<T>
 { };

template <typename T>
struct isCFloating<std::complex<T>> : public std::true_type
 { };

现在你可以编写矢量矢量版本(拦截混合std::vector / QVector案例)如下

template <template <typename ...> class V1,
          template <typename ...> class V2, typename T>
auto loadData (V1<V2<T>> & v, std::string fn)
   -> std::enable_if_t<   isVector<V1>::value
                       && isVector<V2>::value
                       && isCFloating<T>::value>
 {
   std::cout << "- vector of vector version, " << fn << std::endl;
 }

之后,简单的矢量版本(包装第一个参数并调用矢量矢量版本)变为

template <template <typename ...> class V, typename T>
auto loadData (V<T> & v, std::string fn)
   -> std::enable_if_t<isVector<V>::value && isCFloating<T>::value>
 {
   std::cout << "- vector version, " << fn << std::endl;

   V<V<T>> vv{1, v};

   loadData(vv, fn);
 }

我已准备好以下完整的工作示例,但(抱歉)我目前没有可用的QT平台,因此我添加了假QVector

#include <vector>
#include <complex>
#include <iostream>
#include <type_traits>

// fake QVector
template <typename>
struct QVector
 { 
   template <typename ... Ts>
   QVector (Ts const & ...)
    { }
 };

template <template <typename...> class>
struct isVector : public std::false_type
 { };

template <>
struct isVector<std::vector> : public std::true_type
 { };

template <>
struct isVector<QVector> : public std::true_type
 { };

template <typename T>
struct isCFloating : public std::is_floating_point<T>
 { };

template <typename T>
struct isCFloating<std::complex<T>> : public std::true_type
 { };


template <template <typename ...> class V1,
          template <typename ...> class V2, typename T>
auto loadData (V1<V2<T>> & v, std::string fn)
   -> std::enable_if_t<   isVector<V1>::value
                       && isVector<V2>::value
                       && isCFloating<T>::value>
 {
   std::cout << "- vector of vector version, " << fn << std::endl;
 }

template <template <typename ...> class V, typename T>
auto loadData (V<T> & v, std::string fn)
   -> std::enable_if_t<isVector<V>::value && isCFloating<T>::value>
 {
   std::cout << "- vector version, " << fn << std::endl;

   V<V<T>> vv{1, v};

   loadData(vv, fn);
 }

int main ()
 {
   std::vector<float>                             vf;
   std::vector<std::complex<float>>               vc;
   std::vector<std::vector<double>>               vvf;
   std::vector<std::vector<std::complex<double>>> vvc;
   QVector<long double>                           qf;
   QVector<std::complex<long double>>             qc;
   QVector<QVector<float>>                        qqf;
   QVector<QVector<std::complex<float>>>          qqc;

   loadData(vf,  "case  1");
   loadData(qf,  "case  2");
   loadData(vc,  "case  3");
   loadData(qc,  "case  4");
   loadData(vvf, "case  5");
   loadData(qqf, "case  6");
   loadData(vvc, "case  7");
   loadData(qqc, "case  8");

   // extra cases: mixing std::vector and QVector

   std::vector<QVector<double>>                    vqf;
   std::vector<QVector<std::complex<double>>>      vqc;
   QVector<std::vector<long double>>               qvf;
   QVector<std::vector<std::complex<long double>>> qvc;

   loadData(vqf, "case  9");
   loadData(vqc, "case 10");
   loadData(qvf, "case 11");
   loadData(qvc, "case 12");
 }

答案 1 :(得分:1)

您可以使用基于模板和迭代器的通用算法来减少代码重复。 例如:

enum class load_data_status 
{
  success
  // something you need
};

template<typename I>
void loadData(const I& first,const I& last, std::ostream& file)
{
  typedef typename std::iterator_traits<I>::value_type T;
  // do load raw data 
  std::for_each(first, last, [file](const T& t) {
    // do something
  } );
}
template<typename I>
void loadComplexData(const I& first,const I& last, std::ostream& file)
{
  typedef typename std::iterator_traits<I>::value_type C;
  typedef typename C::value_type T;
  // do load complex data
  std::for_each(first, last, [file](const C& t) {
    // do something
  } );
}

template<typename T>
load_data_status loadData(const std::vector< std::vector<T> >& data, const std::string& file) {
  std::ofstream f(file);
  std::for_each(data.cbegin(), data.cend(), [f] (const std::vector<T>& v) {
     loadData(v.cbegin(), v.cend(), f);
  } );
  return load_data_status::success;
}
template<typename T>
load_data_status loadData(const QVector< QVector<T> >& data, const std::string& file) {
 std::ofstream f(file); 
 std::for_each(data.begin(), data.end(), [f] (const QVector<T>& v) {
     loadData(v.begin(), v.end(), f);
  } );
  return load_data_status::success;
} 
template<typename T>
load_data_status loadData(const std::vector< std::vector<std::complex<T> > >& data, const std::string& file) {
  std::ofstream f(file); 
  std::for_each(data.cbegin(), data.cend(), [f] (const std::vector<std::complex<T> >& v) {
     loadComplexData(v.cbegin(), v.cend(), f);
  } );
  return load_data_status::success;
}
template<typename T>
load_data_status loadData(const QVector< QVector< std::complex<T> > >& data, const std::string& file) {
  std::ofstream f(file); 
  std::for_each(data.begin(), data.end(), [f] (const QVector< std::complex<T> >& v) {
     loadComplexData(v.begin(), v.end(), f);
  } );
  return load_data_status::success;
} 

答案 2 :(得分:1)

编写通用代码时,请特别注意分离问题。

loadData有两个问题: -

  • 从文件中获取对象
  • 将这些对象附加到容器

因此,让我们构建一个模板,作为数据源(我们可以根据值类型进行专门化),然后按照这种方式为每个容器类型写一个重载。

首次尝试:

#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <complex>

struct data_file_loader_base
{
    data_file_loader_base(std::string const& path)
    : input_stream_(path)
    , items_(get_input<std::size_t>())
    {

    }

    template<class T>
    T get_input()
    {
        T val;
        input_stream_ >> val;
        return val;
    }

    std::size_t items() const
    {
        return items_;
    }

    std::ifstream& input_stream()
    {
        return input_stream_;
    }

private:
    std::ifstream input_stream_;
    std::size_t items_;
};

// basic value loader
template<class Type>
struct data_file_loader
: data_file_loader_base
{
    data_file_loader(std::string const& path)
    : data_file_loader_base(path)
    {}

    std::istream_iterator<Type> begin()
    {
        return { input_stream() };
    }

    std::istream_iterator<Type> end()
    {
        return { };
    }
};

// specialize for types that need custom input
// in this case, for a complex. But could easily be a vector etc.
template<class Type>
struct data_file_loader<std::complex<Type>>
: data_file_loader_base
{
    data_file_loader(std::string const& path)
    : data_file_loader_base(path)
    {}

    struct iterator
    {
        using value_type = std::complex<Type>;
        using iterator_category = std::forward_iterator_tag;
        using pointer = value_type*;
        using reference = value_type&;
        using difference_type = int;

        iterator(data_file_loader& loader, bool eof = false)
        : self_(loader)
        , eof_(eof || check_eof())
        {
        }

        bool operator==(iterator const& other) const
        {
            return eof_ && other.eof_;
        }

        bool operator!=(iterator const& other) const
        {
            return !(*this == other);
        }

        iterator& operator++() {
            return *this;
        }

        value_type operator*() {
            auto result = value_type { self_.get_input<Type>(), self_.get_input<Type>() };
            eof_ = check_eof();
            return result;
        }

        bool check_eof() const {
            return !input_stream();
        }

        data_file_loader& self_;
        bool eof_ = false;
    };

    iterator begin()
    {
        return { *this, false };
    }

    iterator end()
    {
        return { *this, true };
    }
};


// one overload per container type
template<class Type>
void loadData(std::vector<Type>& target, std::string const& path)
{
    auto loader = data_file_loader<Type>(path);
    target.reserve(loader.items());
    std::copy(std::begin(loader), std::end(loader), std::back_inserter(target));
}

// test
int main()
{
    std::vector<int> vi;
    loadData(vi, "foo.txt");

    std::vector<std::complex<double>> vc;
    loadData(vc, "foo_complex.txt");
}