【问题标题】:How can I return a dependent type from templated class method?如何从模板化类方法返回依赖类型?
【发布时间】:2015-04-03 17:13:57
【问题描述】:

假设我有一个基于模板ThingType 的课程。在标题中,我使用它来typedef 一个依赖类型VectorThingType。我想从方法GetVectorOfThings() 中返回它。如果我将VectorThingType 设置为返回类型,则会收到Does not name a type 错误,因为该类型未在此范围内定义。有没有什么方法可以在不复制typedef中的代码的情况下做到这一点?

#include <vector>
#include <iostream>

template< typename ThingType >
class Thing
{
public:

 ThingType aThing;
 typedef std::vector< ThingType > VectorThingType;
 VectorThingType GetVectorOfThings();

Thing(){};
~Thing(){};

};

template< typename ThingType >
//VectorThingType // Does not name a type 
std::vector< ThingType > // Duplication of code from typedef
Thing< ThingType >
::GetVectorOfThings() {
  VectorThingType v;
  v.push_back(this->aThing);
  v.push_back(this->aThing);
  return v;
}

【问题讨论】:

    标签: c++ class templates typedef


    【解决方案1】:
    template< typename ThingType >
    auto // <-- defer description of type until...
    Thing< ThingType >
    ::GetVectorOfThings()
    -> VectorThingType // <-- we are now in the context of Thing< ThingType >
    {
      VectorThingType v;
      v.push_back(this->aThing);
      v.push_back(this->aThing);
      return v;
    }
    

    【讨论】:

      【解决方案2】:

      刚刚遇到这个问题的另一个答案,不涉及c++11。

      template< typename ThingType >
      typename Thing< ThingType >::VectorThingType
      Thing< ThingType >
      ::GetVectorOfThings()
      {
        VectorThingType v;
        v.push_back(this->aThing);
        v.push_back(this->aThing);
        return v;
      }
      

      基本上涉及向编译器保证您实际上是通过typename 处理一个类型,然后使用Thing&lt; ThingType &gt;:: 正确地确定该类型的范围。如果您因某种原因被 c++03 卡住,可能会很有用。

      【讨论】:

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