接受 std::vector 和 QVector 的函数模板?
A function template that accepts both std::vector and QVector?
假设我有一个名为 loadData()
的函数,它接受一个容器(用于填充数据)和一个 CSV 文件。我需要以下重载:
loadData(std::vector<double>& data, const std::string& file);
loadData(QVector<double>& data, const std::string& file);
loadData(std::vector<std::complex<double>>& data, const std::string& file);
loadData(QVector<std::complex<double>>& data, const std::string& file);
loadData(std::vector<std::vector<double>>& data, const std::string& file);
loadData(QVector<QVector<double>>& data, const std::string& file);
loadData(std::vector<std::vector<std::complex<double>>>& data, const std::string& file);
loadData(QVector<QVector<std::complex<double>>>& data, const std::string& file);
QVector
是 Qt 的类向量 class,具有类似的 API,但只采用一个模板参数 T
(而不是两个,如 std::vector<T, A>
).
1-4 的实现几乎相同(它只是调用 5-8,将单个向量包装在另一个向量(相同类型!)中。
5-8 的实现是相同的(只是调用了 CSV 解析函数的适当重载)。
我可能还需要添加 float
重载,或 QVector<std::vector<...>>
/ std::vector<QVector<...>>
重载。
基本上,这是我想概括的大量重载。
是否可以将它们全部组合成 2 个功能模板(一个用于 1D 容器,另一个用于 2D 容器)?
谢谢
您可以使用基于模板和迭代器的通用算法来减少代码重复。
例如:
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");
}
Is it possible to combine all of them into maybe 2 function templates (one for 1D containers, another for 2D containers)?
是的...需要一些工作但相对简单。
也许有更简单的方法,但我建议创建一个自定义类型特征来验证模板模板是 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");
}
假设我有一个名为 loadData()
的函数,它接受一个容器(用于填充数据)和一个 CSV 文件。我需要以下重载:
loadData(std::vector<double>& data, const std::string& file);
loadData(QVector<double>& data, const std::string& file);
loadData(std::vector<std::complex<double>>& data, const std::string& file);
loadData(QVector<std::complex<double>>& data, const std::string& file);
loadData(std::vector<std::vector<double>>& data, const std::string& file);
loadData(QVector<QVector<double>>& data, const std::string& file);
loadData(std::vector<std::vector<std::complex<double>>>& data, const std::string& file);
loadData(QVector<QVector<std::complex<double>>>& data, const std::string& file);
QVector
是 Qt 的类向量 class,具有类似的 API,但只采用一个模板参数 T
(而不是两个,如 std::vector<T, A>
).
1-4 的实现几乎相同(它只是调用 5-8,将单个向量包装在另一个向量(相同类型!)中。
5-8 的实现是相同的(只是调用了 CSV 解析函数的适当重载)。
我可能还需要添加 float
重载,或 QVector<std::vector<...>>
/ std::vector<QVector<...>>
重载。
基本上,这是我想概括的大量重载。
是否可以将它们全部组合成 2 个功能模板(一个用于 1D 容器,另一个用于 2D 容器)?
谢谢
您可以使用基于模板和迭代器的通用算法来减少代码重复。 例如:
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");
}
Is it possible to combine all of them into maybe 2 function templates (one for 1D containers, another for 2D containers)?
是的...需要一些工作但相对简单。
也许有更简单的方法,但我建议创建一个自定义类型特征来验证模板模板是 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");
}