此代码无法在 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++ Optimizing Compiler Version 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
的标准引用disambiguator 是 C++11 标准的第 14.2/4 段:
When the name of a member template specialization appears after
.
or->
in a postfix-expression or after a nested-name-specifier in a qualified-id, and the object expression of the postfix-expression is type-dependent or the nested-name-specifier in the qualified-id refers to a dependent type, but the name is not a member of the current instantiation (14.6.2.1), the member template name must be prefixed by the keywordtemplate
. Otherwise the name is assumed to name a non-template.[ Example: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 }
—end example ]
关于c++ - g++ 中 ">"之前的预期主表达式,但在微软编译器中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15572415/