c++ - 未使用依赖类型的“预期主表达式”错误

标签 c++ templates methods

在下面的代码中,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/

相关文章:

c++ - boost::interprocess - allocate_aligned 在共享内存中?

java - 递归地将数字总和减少到一位数

c++ - 使用蒙版获取图像像素

c++ - 声明一个与给定模板参数的函数具有相同签名的函数

java - 如何在 Eclipse 中删除模板

javascript - Jade模板,扩展模板后添加到头部

java - Java 中的通用静态方法

python - 将属性分配给类方法

c++ - 为什么 C++ 中的多重定义错误不是由 const int 声明引起的?

c++ - QTranslator:为什么app有些地方没有翻译?