繁体   English   中英

预期在g ++中“>”之前的primary-expression,但不在microsoft编译器中

[英]expected primary-expression before “>” in g++ but not in microsoft compiler

此代码无法在g ++(Ubuntu / Linaro 4.6.3-1ubuntu5)4.6.3上编译,出现此错误

test.cpp: In function ‘T mul(V&, V&)’:
test.cpp:38:27: error: expected primary-expression before ‘>’ token
test.cpp:38:29: error: expected primary-expression before ‘)’ token
test.cpp:38:53: error: expected primary-expression before ‘>’ token
test.cpp:38:55: error: expected primary-expression before ‘)’ token

但它在Microsoft C / C ++优化编译器版本15.00.21022.08 for x64上正确编译和执行

#include <iostream>
#include <complex>

template <class T>
class SM
{
public:
    T value;
};

template <class T>
class SC : public SM<T>
{
};

class PSSM {

public:
    template <class T>
    T & getSC() { return sc; }

private:
    SC<double> sc;
};

class USSM {

public:
    template <class T>
    T & getSC() { return sc; }

private:
    SC<std::complex<double> > sc;
};

template <class T, class V>
T mul( V & G, V & S) {
    return (G.getSC<SC<T> >().value * S.getSC<SC<T> >().value); // error is here
}


int main() {
    PSSM p;
    PSSM q;
    p.getSC<SC<double> >().value = 5; 
    q.getSC<SC<double> >().value = 3; 

    std::cout << mul<double>(p,q);

}

我不明白问题出在哪里。 谁能理解如何解决它,或解释g ++中问题的本质?

问题是语法问题。 在这种情况下,您应该使用template消歧器,以便正确解析您对成员函数模板的调用:

return (G.template getSC<SC<T> >().value * S.template getSC<SC<T> >().value);
//        ^^^^^^^^^                          ^^^^^^^^^

这个消歧器帮助编译器识别G.成员模板特化,而不是例如名为getSC的数据成员后跟< (小于)。

template消除器的标准参考是C ++ 11标准的第14.2 / 4段:

当成员模板专业化的名称出现之后. 或者->在postfix-expression中或者在qualified-id中nested-name-specifier之后, postfix-expression的对象表达式依赖于类型,或者qualified-id中的nested-name-specifier指的是依赖类型,但名称不是当前实例化的成员 (14.6.2.1), 成员模板名称必须以关键字template为前缀。 否则,假定该名称命名非模板。 [ 例如:

 struct X { template<std::size_t> X* alloc(); template<std::size_t> static X* adjust(); }; template<class T> void f(T* p) { T* p1 = p->alloc<200>(); // ill-formed: < means less than T* p2 = p->template alloc<200>(); // OK: < starts template argument list T::adjust<100>(); // ill-formed: < means less than T::template adjust<100>(); // OK: < starts template argument list } 

- 结束例子 ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM