如何在C++中实现static_cast

Mar*_*dik 1 c++ gmp static-cast eigen

我试图将GMP数字库与特征矩阵库一起使用.我尝试实例化模板:

Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
Run Code Online (Sandbox Code Playgroud)

Matrix<mpz_class, 3, 3> matrix;
Run Code Online (Sandbox Code Playgroud)

其中mpz_class是GMP库中的数字类.

我收到编译器错误:

 /usr/include/eigen3/Eigen/src/Core/MathFunctions.h:409: error: 
 invalid static_cast from     
 type ‘const __gmp_expr<__mpz_struct [1], __mpz_struct [1]>’ 
 to type ‘int’
Run Code Online (Sandbox Code Playgroud)

当我检查Eigen库的源代码时,我发现问题是mpz_class在这个模板中不能是static_cast -ed到int:

template<typename OldType, typename NewType>
struct cast_impl
{
  static inline NewType run(const OldType& x)
  {
    return static_cast<NewType>(x);
  }
};
Run Code Online (Sandbox Code Playgroud)

我该如何绕过这个问题?我知道如何在运行时将mpz_class转换为int,但它必须由编译器完成,因为static_cast是编译时.

Kle*_*ist 6

如果您知道如何实现它,则可以对cast_impl模板类进行专门化.

template <>
struct cast_impl<Type1, Typ2>
{
    static inline Type2 run(const Type1&x) {
        // Conversion here returning Type2 from Type1
    }
}
Run Code Online (Sandbox Code Playgroud)

Type1和Type 2应该替换为您的情况中的实际类型.


ues*_*esp 5

除了其他答案之外,您可能还需要阅读" Eigen:使用自定义标量类型 "以了解使用自定义标量类的其他要求,这些要求可能会在某些时候出现.