返回对模板向量的引用

时间:2014-06-12 18:38:25

标签: c++ templates vector reference

我从简单的类声明开始,我在其中定义了内联模板方法,该方法返回对specyfic类型容器的引用。

class JPetParamManager
{
public:
  enum ContainerType {kScintillator, kPM, kKB, kTRB, kTOMB};

  std::vector<JPetScin> fScintillators;
  std::vector<JPetPM>   fPMs;
  std::vector<JPetKB>   fKBs;
  std::vector<JPetTRB>  fTRBs;
  std::vector<JPetTOMB> fTOMBs;

  template <typename T>
  const std::vector<T>& getContainer(const JPetParamManager::ContainerType &p_containerType) const
  {
    switch(p_containerType) 
    {
    case kScintillator:
      return fScintillators;
    case kPM:
      return fPMs;
    case kKB:
      return fKBs;
    case kTRB:
      return fTRBs;
    case kTOMB:
      return fTOMBs;
    }
  }
}

在另一个类方法中,我想从上面的类中返回一些容器:

void JPetAnalysisModuleKB::CreateOutputObjects(const char* outputFilename)
{
  std::vector<JPetKB> l_KBs22 = m_manager.getParamManagerInstance().getContainer<JPetKB>(JPetParamManager::ContainerType::kKB);
}

当我想在main中运行此方法时,我遇到如下错误:

./../../framework/JPetManager/../JPetParamManager/JPetParamManager.h: In member function ‘const std::vector<_RealType>& JPetParamManager::getContainer(const JPetParamManager::ContainerType&) const [with T = JPetKB]’:
JPetAnalysisModuleKB.cpp:55:126:   instantiated from here
./../../framework/JPetManager/../JPetParamManager/JPetParamManager.h:81:14: error: invalid initialization of reference of type ‘const std::vector<JPetKB>&’ from expression of type ‘const std::vector<JPetScin>’
./../../framework/JPetManager/../JPetParamManager/JPetParamManager.h:83:14: error: invalid initialization of reference of type ‘const std::vector<JPetKB>&’ from expression of type ‘const std::vector<JPetPM>’
./../../framework/JPetManager/../JPetParamManager/JPetParamManager.h:87:14: error: invalid initialization of reference of type ‘const std::vector<JPetKB>&’ from expression of type ‘const std::vector<JPetTRB>’
./../../framework/JPetManager/../JPetParamManager/JPetParamManager.h:89:14: error: invalid initialization of reference of type ‘const std::vector<JPetKB>&’ from expression of type ‘const std::vector<JPetTOMB>’
make: *** [JPetAnalysisModuleKB.o] Błąd 1

1 个答案:

答案 0 :(得分:2)

简介

即使只有一个开关标签匹配并执行,与其他标识相关联的语句仍必须有效。

编译器试图告诉您,在返回std::vector<T> const&(其中T是传递给您的函数的类型)时,并非所有返回都可以使用。


解释

以下实例化getContainer的方式使其返回std::vector<PetKB>,但在实例化该函数时,编译器将看到 case-label kScintillator 的返回类型为std::vector<JPetScin>

m_manager.getParamManagerInstance().getContainer<JPetKB> (JPetParamManager::kScintillator)

由于std::vector<JPetScin>无法转换为std::vector<PetKB>编译器抱怨,并且基本上说您的代码格式不正确。

即使 switch-condition 没有选择返回类型不同的 case ,这同样适用; 所有路径必须能够返回,否则应用程序格式不正确。