【发布时间】:2016-10-23 00:05:39
【问题描述】:
我当前的代码如下所示:Code here
我有一个模板ClassOuter 和一个嵌套模板ClassInnerBase,其中TypeD 可以是TypeA, TypeB, TypeC 的任何类型,不能是其他类型。此外,ClassInnerDerived 应该继承自 ClassInnerBase 并实现 virtual const int Method(int id) = 0;。
template<typename TypeA, typename TypeB, typename TypeC>
class ClassOuter {
public:
class ClassInnerBase {
public:
ClassInnerBase(int x) :
m_x(x) {
}
virtual const int Method(int id) = 0;
private:
int m_x;
};
template<typename TypeD>
class ClassInnerDerived : public ClassInnerBase {
public:
ClassInnerDerived<TypeD>(const TypeD &object, int x) :
ClassInnerBase(x), m_object(object) {
}
// Implementation of ClassInnerBase::Method for type float
template<>
const int ClassInnerDerived<float>::Method(int id){
return GetLookupID(id);
}
// Implementation of ClassInnerBase::Method for type double
template<>
const int ClassInnerDerived<double>::Method(int id){
return GetLookupID(id);
}
private:
TypeD m_object;
};
void DoSomething(const std::vector<ClassInnerBase> &inner_vec, int id);
const int GetLookupID(int id) const{
return lookup[id];
}
private:
int lookup[100];
};
template<typename TypeA, typename TypeB, typename TypeC>
void ClassOuter<TypeA, TypeB, TypeC>::DoSomething(const std::vector<ClassInnerBase> &inner_vec, int id){
for(const auto &inner : inner_vec){
inner.Method(id);
}
}
int main()
{
std::vector<typename ClassOuter<int, double, float>::ClassInnerBase> class_base_objects;
typename ClassOuter<int, double, float>::template ClassInnerDerived<float> class_inner_derived_object(0.2f, 1);
class_base_objects.push_back(class_inner_derived_object);
typename ClassOuter<int, double, float>::template DoSomething(class_base_objects, 1);
}
我最终得到了错误:
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp:30:18: error: explicit specialization in non-namespace scope 'class ClassOuter<TypeA, TypeB, TypeC>::ClassInnerDerived<TypeD>'
template<>
^
我被困在这里,不知道如何解决这个错误。 另外,ifself 的实现有什么建议/cmets/改进吗?
【问题讨论】:
-
您最好在Code Review 上更好地改进您的实施
-
@Rakete1111 不,代码审查不是用于存放损坏代码的地方,因为它在那边是题外话。他在正确的网站上问了。
-
@syb0rg 我只指改进位。对于实际错误,OP 在正确的站点上
标签: c++ class templates inheritance nested