【发布时间】:2014-06-12 18:38:25
【问题描述】:
我从简单的类声明开始,我定义了内联模板方法,该方法返回对特定类型容器的引用。
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
【问题讨论】:
-
编译器说的是返回类型(即右侧)与
std::vector<JPetKB> l_KBs22(即左侧)不匹配。 -
仅仅因为您说
getContainer<JPetKB>(...)并不意味着编译器可以忽略其余case语句中的类型不匹配! -
模板参数和函数参数不是多余的吗?
标签: c++ templates vector reference