gpt4 book ai didi

C++ 模板函数 -> 将模板类作为模板参数传递

转载 作者:太空狗 更新时间:2023-10-29 21:30:22 25 4
gpt4 key购买 nike

我尝试大量使用模板来包装工厂类:

包装类(即 classA)通过模板参数获取包装类(即 classB)以提供“可插入性”。

此外,我必须提供一个继承自包装内部类 (innerB) 的内部类 (innerA)。

问题是 g++“gcc 版本 4.4.3 (Ubuntu 4.4.3-4ubuntu5)”的以下错误消息:

sebastian@tecuhtli:~/Development/cppExercises/functionTemplate$ g++ -o test test.cpp
test.cpp: In static member function ‘static classA<A>::innerA<iB>* classA<A>::createInnerAs(iB&) [with iB = int, A = classB]’:
test.cpp:39: instantiated from here
test.cpp:32: error: dependent-name ‘classA::innerA<>’ is parsed as a non-type, but instantiation yields a type
test.cpp:32: note: say ‘typename classA::innerA<>’ if a type is meant

正如您在方法 createInnerBs 的定义中看到的,我打算传递一个非类型参数。所以typename的使用是错误的!

test.cpp代码如下:

class classB{
public:
template < class iB>
class innerB{
iB& ib;
innerB(iB& b)
:ib(b){}
};

template<template <class> class classShell, class iB>
static classShell<iB>* createInnerBs(iB& b){
// this function creates instances of innerB and its subclasses,
// because B holds a certain allocator

return new classShell<iB>(b);
}
};

template<class A>
class classA{
// intention of this class is meant to be a pluggable interface
// using templates for compile-time checking
public:
template <class iB>
class innerA: A::template innerB<iB>{
innerA(iB& b)
:A::template innerB<iB>(b){}
};

template<class iB>
static inline innerA<iB>* createInnerAs(iB& b){
return A::createInnerBs<classA<A>::template innerA<> >(b); // line 32: error occurs here
}
};

typedef classA<classB> usable;
int main (int argc, char* argv[]){
int a = 5;
usable::innerA<int>* myVar = usable::createInnerAs(a);

return 0;
}

请帮帮我,我已经面对这个问题好几天了。这是不可能的,我想做什么?还是我忘记了什么?

谢谢,塞玛

最佳答案

第 32 行应为:

return A::template createInnerBs<innerA>(b);

因为 createInnerBs 依赖于模板参数 A

您还需要公开innerAinnerB 的构造函数。

关于C++ 模板函数 -> 将模板类作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com