我有一个关于(我认为) C++ (在C++11之前,我现在还不能升级)模板编程(和“特性”)的问题。
我的目标是:
我有不同(但非常相似)的类(已经从具有新功能和成员的基类派生了类)。
我编写了一个模板类,它继承了这些类中的任何一个,并使用多态函数“open”从数据库中收取与特定类相关的所有成员和信息。
我之所以想到这个策略,是因为在我想要使用这个实例化类(及其所有成员)作为其他函数的输入之后。我本可以做到的(我想..。但是在这里,我的模板类可以从模板参数…中的类继承)有一个开关/用例架构,但是我想在这里避免它,因为它后来已经被大量使用了。
例如,我有类Derived1和Derived2 (定义在Derived.hpp文件中),它们覆盖了它们的根父类打开的函数。我有一个模板函数MyClass,它曾经像MyClass < DerivedType1> currentClass()或MyClass < DerivedType2> currentClass()一样使用,可以做我想做的事情(下面的代码)。
问题:
是否有可能编写一些东西,使我有可能生成一个for循环?
有点像
For (auto i=1; i<N; ++i)
{
MyClass<DerivedType[i]> currentClass();
--- other things to do with my currentClass ---
}现在,我的DerivedType是“type”(参见下面traits.hpp片段中的结构),我甚至不知道是否可以将它们放入容器(如向量)…中。也许在C++11中,我可以为所有的DerivedTypes定义一个枚举类(这是真的吗?),但是这里有C++03?
完全迷失了,我承认…
,谢谢您的建议。。
(工作)主要
(包括“MyClass.hpp”)
int main(int, char* [])
{
GlobalClass GlobalItem(); //global class encapsulating all the info of each item from the database
//connection to the database
//DerivedType1 case
MyClass<DerivedType1> CurrentClass();
GlobalItem.AddCurrentClass();
//with a for loop or the like I can use the fact that at each loop the class is declared only inside the { … } and then each time the destructor
//is automatically called
CurrentClass.clear();
CurrentClass = MyClass<DerivedType2>();
GlobalItem.AddCurrentClass();
return 0;
}下面是模板类MyClass.hpp:
(包括“traits.hpp”)
template <class Traits>
class MyClass : public Traits::type
{
private:
typedef typename Traits::type BaseType;
protected:
std::string currentType_;
public:
//constructor
MyClass() : BaseType() { this->open() }
//destructor
virtual ~MyClass();
};在这里,由作用域::operator运行的traits.hpp文件
(包括"Derived.hpp")
struct DerivedType1 {
typedef Derived1 type;
};
struct DerivedType2 {
typedef Derived2 type;
};发布于 2014-12-08 12:24:34
模板在编译时实例化,for()循环在运行时进行评估。
所以不你不能这么做。
要在模板定义上“循环”,您可以拥有类似的构造。
template<int N>
struct A {
typedef A<N - 1> X;
};
template<>
struct A<0> {
typedef void X;
};发布于 2014-12-08 14:01:03
使用各种模板,您可以执行如下操作:
template <typename T>
void do_job()
{
// job for one type
// MyClass<T> currentClass;
// ...
}
template <typename ... Ts>
void do_jobs()
{
// trick to unroll the types sequentially
std::initializer_list<int>{(do_job<Ts>(), 0)...};
}并称之为:
do_jobs<Derived1, Derived2>();https://stackoverflow.com/questions/27357927
复制相似问题