【问题标题】:Return a struct declared inside template class from a template method [duplicate]从模板方法返回在模板类中声明的结构[重复]
【发布时间】:2018-03-08 21:48:10
【问题描述】:

我有以下几点:

#include <vector>

template <class T>
class A
{
public:
    struct S
    {
        int a;
    };

    std::vector<S>  returnStructs(void);
};

template <class T>
std::vector<A<T>::S>    A<T>::returnStructs(void)
{
}

int main(void)
{
}

但是当我尝试编译时,我得到:

error: template argument for template type parameter must be a type; did you forget
      'typename'?
std::vector<A<T>::S>    A<T>::returnStructs(void)
            ^
            typename

所以我把那行换成了:

std::vector<A<int>::S>  A<T>::returnStructs(void)
              ^
              'int' instead of 'T'

然后我得到一个新的编译器错误:

error: return type of out-of-line definition of 'A::returnStructs' differs from that in the
      declaration
std::vector<A<int>::S>  A<T>::returnStructs(void)
~~~~~~~~~~~~~~~~~~~~~~        ^

对如何解决这个问题有什么想法吗?


我也意识到我可以将 struct S 从 A 类中取出并解决所有这些问题,但我仍然觉得应该可以在不更改 A 类的情况下解决这个问题。

【问题讨论】:

    标签: c++ c++11 templates compiler-errors nested


    【解决方案1】:

    第一个编译器错误告诉你到底出了什么问题:did you forget 'typename'

    由于 S 是模板的成员,您需要添加 typename 来告诉编译器它应该延迟名称的查找,直到模板被解析之后:

    template <class T>
    std::vector<typename A<T>::S>    A<T>::returnStructs(void)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      相关资源
      最近更新 更多