【问题标题】:C++ class follows with template keywordC++ 类后跟模板关键字
【发布时间】:2017-07-19 07:24:57
【问题描述】:

我正在编译一个使用 C++ 数学库 Eigen3 的 C++ 库。但是,以下代码在使用 VC2013 编译时会引入一些语法错误:

template <typename Derived>
    inline Eigen::Transform<typename Derived::Scalar, 3, Eigen::Isometry> v2t(const Eigen::MatrixBase<Derived>& x_) {
    Eigen::Transform<typename Derived::Scalar, 3, Eigen::Isometry> X;
    Eigen::Matrix<typename Derived::Scalar, 6, 1> x(x_);
    X.template linear() = quat2mat(x.template block<3,1>(3,0));
    X.template translation() = x.template block<3,1>(0,0);
    return X;
  }

错误信息如下:

Error   C2059   syntax error : 'template'    
Error   C2039   'X' : is not a member of 'Eigen::Transform<float,3,1,0>'        
Error   C2059   syntax error : 'template'    
Error   C2039   'X' : is not a member of 'Eigen::Transform<float,3,1,0>'    

我从未见过像X.template 这样的代码,所以我不知道如何纠正这个编译错误。有任何想法吗?

【问题讨论】:

  • 您使用的是什么版本的 Eigen?我抓住了最新的副本,但找不到该代码...库中的代码是您编译的然后引用 Eigen 的吗? .. X.template linear() 应该类似于 X.template linear&lt;Lower&gt;() 或只是 X.linear() ..
  • @txtechhelp 我没有编译Eigen,它是一个使用Eigen的库jacoposerafin.com/nicp
  • X.templatex.template 不是有效的 C++;你打算这些表达是什么意思?
  • 这实际上是有效的 C++。这是一个template 消歧器,从this question 开始。诚然不是一个广泛使用的功能,可能是 VS2013 编译器的问题。
  • 它看起来像一个模板函数,可能在 Windows 中引用,而不是其他平台(或类似的东西);因为模板推导(因此错误)仅在引用该函数时才会发生。并且根据Eigen::Transform docs,该函数不是模板函数,因此不需要template 消歧器(因此会出现错误)。由于它在第 3 方库而不是 Eigen 中,您是否尝试过简单地删除 template 消歧器?

标签: c++ c++11


【解决方案1】:

此处应使用template 关键字来消除模板和比较运算符之间的歧义,例如:

struct X {
    template <int A>
    void f();
};

template <class T>
void g() {
    T t{};
    t.f<4>(); // Error - Do you want to compare t.f with 4 
              // or do you want to call the template t.f ?
}

这里你需要t.template f&lt;4&gt;() 来“消除歧义”。您使用的库的问题是Eigen::Transform&lt;...&gt;::linear 不是模板成员函数,因此这里不需要template 关键字,也不应该使用(我认为)。

[temps.name#5]

以关键字template 为前缀的名称应该是一个template-id,或者这个名称应该是一个类模板。 [ 注意: 关键字template 可能不适用于类模板的非模板成员。 -结尾 注意] [...]

MSVC 是对的,Eigen::Transform&lt;...&gt;::linear 是类模板的非模板成员,因此不应应用 template 关键字。标准中的以下示例应该是格式错误的,但使用 gcc 和 clang 可以很好地编译:

template <class T> struct A {
    void f(int);
    template <class U> void f(U);
};

template <class T> void f(T t) {
    A<T> a;
    a.template f<>(t); // OK: calls template
    a.template f(t); // error: not a template-id
}

关于您在github 上使用的库已经存在一个未解决的问题,但作者没有任何答案...您可以自己更新标题 (ncip/bm_se3.h) 或 fork 项目并进行拉取- github上的请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2018-03-24
    • 2022-12-08
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多