为基本和本征数据类型编写模板函数

问题描述 投票:1回答:2

我如何编写同时包含基本数据类型(int,float,double,…)和本征库类型(Vector2f,Vector4d,Matrix4f等)的函数?具体来说,我想要一个将提供的参数强制转换为类型N的强制转换函数。

例如:

float x1 = cast<float>(1);
double x2 = cast<double>(2.0);
Vector2d x3 = cast<double>(Vector2f(3.0f, 3.0f));
Vector2f x4 = cast<float>(Vector2i(4, 4));

最简单的部分:

template<typename T, typename N>
N cast(const T& source) const
{
    return static_cast<N>(source);
}

投射特征类型:

template<typename T, typename N>
Eigen::CwiseUnaryOp<Eigen::internal::scalar_cast_op<typename Eigen::internal::traits<T>::Scalar, N>, const T> cast(const Eigen::MatrixBase<T>& source) const
{
    return source.cast<N>();
}

在Eigen中,使用v.cast<double>()完成了从Vector2f v到Vector2d的转换,因此template参数是标量的数据类型,而不是新类型本身。

我遇到的麻烦(至少我认为这是主要问题)是我不知道如何将这两个模板放在一起。本征特征可能应该是第一个特征的专业化,但这有可能吗?模板本身可以编译,但是例如cast<Vector2f, double>(Vector2f::Zero())不会,因为'static_cast':无法从'const Eigen :: Vector2f'转换为'double'

该怎么办?非常欢迎使用C ++ 11解决方案,但是请缓慢输入,因为我不是模板向导。

更新:我之所以需要它,是因为我希望能够方便地将容器的内容从std::vector<T>转换为std::vector<N>,例如从std::vector<Vector2f>转换为std::vector<Vector2d>,也可以从std::vector<float>转换为std::vector<double>。为此,我遍历所有元素并使用所需的函数强制转换每个元素。因此,如果有更好的方法来转换本征类型的std :: vector,这将是我所需要的。

c++ templates c++11 eigen eigen3
2个回答
3
投票

您可以使用std::enable_if将常规版本限制为仅算术类型:

template<typename T, typename N>
typename std::enable_if<std::is_arithmetic<T>::value,N>::type
cast(const T& source) const {
  return static_cast<N>(source);
}

0
投票

[使用C ++ 17,还有另一种解决方案,我个人认为使用if constexpr更优雅:

template<typename T, typename N>
std::conditional<std::is_arithmetic<T>::value, N, /* your Eigen return type here */>::type
cast( const T& source ) {
    if constexpr( std::is_arithmetic<T>::value )
        return static_cast<N>(source);
    else
        /* Eigen cast */
}

这样,它全都在一个函数中,我发现语法更清晰。

© www.soinside.com 2019 - 2024. All rights reserved.