针对不同数据类型的单一结构调整方法
Single struct adjusting methods to different data types
我有四个非常相似的结构体(非常简单地说明问题),不同的参数类型
using state_type = std::vector<double>;
struct foo {
double _x;
double _y;
foo (double x, double y) : _x{x}, _y{y} {}
void operator() (const state_type &v, state_type &u) const {
for (auto i=0; i<v.size(); i++)
u[i] = x * v[i] + y * v[i];
}
}
struct foo {
state_type _x;
double _y;
foo (state_type x, double y) : _x{x}, _y{y} {}
void operator() (const state_type &v, state_type &u) const {
for (auto i=0; i<v.size(); i++)
u[i] = x[i] * v[i] + y * v[i];
}
}
struct foo {
double _x;
state_type _y;
foo (double x, state_type y) : _x{x}, _y{y} {}
void operator() (const state_type &v, state_type &u) const {
for (auto i=0; i<v.size(); i++)
u[i] = x * v[i] + y[i] * v[i];
}
}
struct foo {
state_type _x;
state_type _y;
foo (state_type x, state_type y) : _x{x}, _y{y} {}
void operator() (const state_type &v, state_type &u) const {
for (auto i=0; i<v.size(); i++)
u[i] = x[i] * v[i] + y[i] * v[i];
}
}
是否有一种方法可以只使用一个结构体,根据参数的类型自动选择正确的结构体?
我将使用模板和辅助函数来推断类型,然后针对各种类型组合对operator()
进行专门化。一个非常简单的例子来说明这一点:
#include <iostream>
#include <vector>
using state_type = std::vector<double>;
template<typename T, typename S>
struct X
{
T _a;
S _b;
X(T a, S b): _a(a), _b(b){}
// specialize this for different types
void operator()(const state_type& v, state_type& u) const
{
std::cout << "default implementationn";
}
};
// specializations of operator() for <state_type, double>
template<>
void X<state_type, double>::operator()(const state_type& v, state_type& u) const
{
std::cout << "<state_type, double> functorn";
}
template<typename T, typename S>
X<T,S> make_X(const T& a, const S& b)
{
return X<T,S>(a,b); // or even return {a, b};
}
int main()
{
state_type st;
auto foo_double_statetype = make_X(st, 42.); // makes X<state_type, double>
foo_double_statetype(st, st); // calls the specialized operator()
auto foo_int_int = make_X(42, 42); // makes X<int, int>
foo_int_int(st, st); // calls the default operator() (non-specialized)
}
Live on Coliru
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 为char数组调整zlib-zpipe
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 如何调整作为结构或类成员的向量的大小?
- 调整结构/字符数组的大小(以减少内存使用)
- 如何调整结构向量的大小
- 调整结构中的向量的大小
- 使用BOOST_FUSION_ADAPT_STRUCT调整结构时编译器错误
- 调整结构的矢量元素的大小 - SEGV
- 调整定义/包含生成的结构以增强::融合
- 为加速融合调整空结构
- C++:调整大小必须在类/结构/联合中
- 在矢量上使用调整大小时,矢量内部结构中的unique_ptr不会编译
- 每个层次结构的单个单一实例继承
- 一种单一的数据结构,用于从脚本中读取任意类型的变量,以便在运行时进行检索和编辑
- 针对不同数据类型的单一结构调整方法
- 如何调整结构元素数组的大小