C++ 针对不同数据类型的单一结构调整方法

C++ 针对不同数据类型的单一结构调整方法,c++,c++11,C++,C++11,我有四个非常相似的结构(很容易说明问题),参数类型不同 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

我有四个非常相似的结构(很容易说明问题),参数类型不同

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];
    }
}
使用state\u type=std::vector;
结构foo{
双x;
双y;
foo(双x,双y):x{x},y{y}{
void运算符()(常数状态类型&v,状态类型&u)常数{

对于(auto i=0;i我将使用一个模板和一个helper函数来推断类型,然后专门化
操作符()
,用于各种类型组合。一个非常简单的示例来说明这一点:

#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 implementation\n";
    }
};

// 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> functor\n";
}

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)
}
#包括
#包括
使用state_type=std::vector;
模板
结构X
{
T_a,;
S_b;
X(ta,sb):_a(a),_b(b){}
//专门针对不同的类型
void运算符()(常数状态类型&v,状态类型&u)常数
{

Std::CUT你的术语有点混淆。<代码> Stutt不存在参数。也因为“结构”或“结构”自从1985以来就不存在于C++中。这些类是类,尽管事实上,你使用了词汇识别为“代码>结构> <代码>的关键字来声明和定义它们。