【发布时间】:2011-09-23 21:58:00
【问题描述】:
所以我试图让一个模板类成为一个容器(稍后将对其进行操作)一组包含的类,这些类也是从模板生成的,并存储在一个向量中。
我正在尝试做的抽象形式如下所示:
template <typename T, size_t numberofapples>
class Apples {
public:
Apples(std::vector<T> appleinfo1, std::vector<T> appleinfo2);
protected:
std::vector<T> apple_stats;
std::vector<T> info1, info2;
};
template <typename T, size_t numberofapples>
Apples<T, numberofapples>::Apples(std::vector<T> appleinfo1, std::vector<T> appleinfo2) : apple_stats(numberofapples, 0){
for (size_t i = 0; i < numberofapples; ++i) {
apple_stats[i] = rand();
}
info1 = appleinfo1;
info2 = appleinfo2;
}
template <typename T, typename FruitType, size_t numberoffruitperbranch>
class Tree {
public:
Tree(size_t numberofbranches, std::vector<T> commonfruitinfo1, std::vector<T> commonfruitinfo2);
protected:
std::vector<FruitType<T, numberoffruitperbranch> > branchset;
};
template <typename T, typename FruitType, size_t numberoffruitperbranch>
Tree<T, FruitType, numberoffruitperbranch>::Tree(size_t numberofbranches, std::vector<T> commonfruitinfo1, std::vector<T> commonfruitinfo2) : {
typename FruitType<T, numberoffruitperbranch> single_fruit(fruitinfo1, fruitinfo2);
branchset.resize(numberofbranches, single_fruit);
//in the un-abstracted version that has nothing to do with fruit, I'd then iterate over the vector and run some internal code on each one
}
目标是我希望能够做类似的事情:
Tree<double, Apples, 10> MyFirstTree(5, vectorofdata, secondvectorofdata);
然而,目前编译器告诉我 FruitType 不是构造函数中的有效模板。事实上,构造函数内的所有内容似乎都超出了范围并被标记,但我不知道为什么。未抽象的版本也确实有一些其他的成员变量和函数,但问题肯定出在外部类容器的构造函数上。
我哪里出错了/如何才能做得更好?
编辑:修复了一些我注意到的编译器错误(我认为)与我在实际应用程序中没有制作的这个简单示例不同
【问题讨论】:
-
这段代码充满了编译器错误。我只能从
typename FruitType<T, numberoffruitperbranch>和std::vector<FruitType> branchset;假设您正在尝试使用相同的参数作为类型(例如Apples<double, 5>)和模板(只是Apples)。你需要下定决心。 -
我不关注你,这可能就是问题所在。最终我有 2 个类,“Apples”和“Tree”。 Apples 包含类型,(本例中为 double),而 tree 最终应包含 apples(本例中为 double)。在所有情况下,Apples 都应该是从模板生成的类型。那不可能吗?向量应该类似于 std::vector
> 吗? -
除了@UncleBens cmets -
class不是Class在c++,std::vector,不是std:vector,结束类用};不是},还有可能更多... -
这些是我在生成上面的抽象示例时犯的简单的编译器拼写错误。我检查了它并修复了指出的那些,然后检查了我的实际代码;这里没有发现任何问题。
标签: c++ class templates nested