在下面的代码中,main() 中的 'bObj->b()' 行可以编译,但是 'cObj->c()' 行会给出一个错误 'expected primary-expression before '>' token'。这与依赖类型无关;在适当的地方添加"template"或"typename"没有帮助。关于问题是什么的任何提示?在此代码的“真实”版本中,函数“b”还有许多其他模板和非模板版本。问题可能只发生在一个地方,而不是其他地方,但我无法确定重要的区别是什么。
#include <boost/shared_ptr.hpp>
class A {};
class D : public A {};
class B
{
public:
template <class T> boost::shared_ptr<T> b() { return boost::shared_ptr<T>(); }
};
class C
{
public:
boost::shared_ptr<A> b() { return boost::shared_ptr<A>(); }
};
int main(int, char **)
{
boost::shared_ptr<C> cObj(new C);
boost::shared_ptr<B> bObj = boost::dynamic_pointer_cast<B>(cObj);
bObj->b<D>();
cObj->b<D>();
}
最佳答案
C
没有成员函数模板,只有一个普通的成员函数。因此,调用 C::b()
cObj->b<D>(); // ERROR!
cObj->b(); // OK
另外:
In the 'real' version of this code, there are many other template and non-template versions of function 'b'.
那么您提供的代码很可能不是您在代码的“真实”版本中遇到的问题的一个很好的例子。
The problem may be only occur in one place and not others, but I haven't been able to determine what may be the important difference.
您最了解您的代码。我们不能对我们看不到的东西做出假设。如果这个答案不能解决您的问题,我认为您应该提供一个更具代表性的示例来说明您的“真实”代码的作用,可能会将其减少到 SSCCE .
关于c++ - 未使用依赖类型的“预期主表达式”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032285/