小编spi*_*nxz的帖子

c ++检查模板参数的嵌套typedef以获取其标量基类型

考虑下面的指数平滑模板类.此类用于以指数方式平滑/过滤顺序数据(请参阅更新方法).Elemtype可能是一个向量,Floattype通常是一个标量.例如

ExponentialSmoother<Eigen::Vector2f, float> x(0.1, Vector2f(0.5, 0.5));
Run Code Online (Sandbox Code Playgroud)

在此示例中,可以避免第二个模板参数Floattype,因为Eigen的Matrix类包含嵌套的typedef以获取标量基类型:

Vector2f::Scalar
Run Code Online (Sandbox Code Playgroud)

将Elemtype和Floatype实例化为浮点数以平滑一维数据也是合理的.在这种情况下,也可以跳过第二个模板参数.

template <class Elemtype, class Floattype>
class ExponentialSmoother
{
public:
    // ctor
    ExponentialSmoother(Floattype alpha, Elemtype& initial_estimate);

    // getters
    inline const Elemtype& getValue() const {return estimate_;}
    inline const Floattype getAlpha() const {return alpha_;}

    const Elemtype& update(const Elemtype& curr)
    {
       estimate_ = (alpha_ * curr) + (((Floattype)1-alpha) * estimate_);
       return estimate_;
    }

private:
    Elemtype estimate_;
    Floattype alpha_;  // smoothing factor within [0,1]
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,只用一个模板参数(元素类型)实现ExponentialSmoother的"最优雅"解决方案是什么?它应该与特征向量和矩阵一起使用,但也适用于浮点类型.

换句话说,是否可以检查Elemtype :: Scalar是否存在,如果不存在(即Elemtype是float还是double),将Floattype定义为Elemtype?

这里也提出类似的问题.但我想知道最通用的解决方案是什么,例如,如果还应支持STL向量.是否所有类型都需要相同的嵌套typedef(或具有一致命名的某些traits类)?

c++ boost traits eigen

5
推荐指数
1
解决办法
855
查看次数

将抽象函子分配给std :: function - 为什么std :: ref是一个解决方案?

我想将函数的赋值封装到std :: function中.我没有传递std :: function或指向std :: function的指针,而是传递从公共抽象类Slot继承的函子(即这些插槽提供了额外的功能).

我在不同的形状偶然发现了这个问题在这里.例如,使用通用槽指针代替std:函数的动机是仿函数的生命周期管理.

以下代码说明了该问题.请参阅assignFunctorPtr(...)方法.

#include <iostream>
#include <functional>

template<class FunSig>
class Slot;

template<class R>
class Slot<R()>
{
public:
    typedef R Ret_type;

public:
    virtual ~Slot() {}
    virtual Ret_type operator()() = 0;
};

template<class R, class A1>
class Slot<R(A1)>
{
public:
    typedef R Ret_type;
    typedef A1 Arg1_type;

public:
    virtual ~Slot() {}
    virtual Ret_type operator()(Arg1_type) = 0;
};

class TestSlot: public Slot<void (float &)>
{
public:
    void operator()(float& f)
    { std::cout << f ;}
};


template<class …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading c++11 std-function

4
推荐指数
1
解决办法
2122
查看次数

标签 统计

c++ ×2

boost ×1

c++11 ×1

eigen ×1

operator-overloading ×1

std-function ×1

traits ×1