簡體   English   中英

同時接受std :: vector和QVector的函數模板?

[英]A function template that accepts both std::vector and 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);

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容器)?

謝謝

是否可以將它們全部組合成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");
 }

您可以使用基於模板和迭代器的通用算法來減少代碼重復。 例如:

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;
} 

在編寫通用代碼時,請特別注意分離關注點。

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM