要在 for 循环中更改的模板参数
Template parameter to change in a for loop?
我有一个与(我认为(C++(在 C++11 之前,我暂时无法升级(模板编程(和"特征"(相关的问题。
我的目标:
我有不同的(但非常相似(的类(已经从具有新功能和成员的基类派生的类(。
我编写了一个 Template 类,该类继承自这些类中的任何一个,并使用多态函数"open"从数据库中收取与特定类相关的所有成员和信息。
我想到这个策略是因为在我想使用这个实例化类(及其所有成员(作为其他函数的输入之后。我本可以使用开关/案例架构来完成它(我认为..但是在这里我的模板类可以从模板参数中的类继承......(,但我想在这里避免它,因为它已经在之后被大量使用。
例如,我有类 Derived1 和 Derived2(在 Derived.hpp 文件中定义(,它们覆盖了它们的根父类的函数打开。我有一个模板函数MyClass曾经使用过 MyClass
问题:
是否可以编写一些让我有可能制作 for 循环的东西?
类似的东西
For (auto i=1; i<N; ++i)
{
MyClass<DerivedType[i]> currentClass();
--- other things to do with my currentClass ---
}
对我来说,现在我的 DerivedType(s( 是"类型"(请参阅下面 traits.hpp 代码段中的结构(,我什至不知道我是否可以将它们放在容器中(如向量(......也许在 C++11 中,我可以为所有派生类型定义一个枚举类(这是真的吗?(,但这里有 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:
(包括"特质.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();
};
这里是由范围 :: 运算符运行的 traits.hpp 文件
(包括"派生.hpp"(
struct DerivedType1 {
typedef Derived1 type;
};
struct DerivedType2 {
typedef Derived2 type;
};
模板在编译时实例化,for()
循环在运行时计算。
所以不,你不能这样做。
要"循环">模板定义,您可以使用诸如
template<int N>
struct A {
typedef A<N - 1> X;
};
template<>
struct A<0> {
typedef void X;
};
使用可变参数模板,您可以执行以下操作:
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>();
- 带有多个独立参数的C++For循环
- C++函数模板需要 &for 数组参数
- C++:关于for语句和参数的一般问题
- C++是否在 for 循环之前获取参数
- 调用模板函数的问题"No matching function for call"参数:迭代器、对象函数
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- C++参数类型以接受适用于基于范围的 for 循环的所有序列
- 为什么我"no matching function for call to .."可变参数模板函数?
- C++函数模板:必须使用 & for 参数类型和返回类型?
- Initializer_list函数参数和函数中的 for 循环
- 搜索参数空间时避免嵌套的 for 循环
- 意外错误"no matching function for call to",需要没有参数的构造函数
- 在for语句参数内部的C/C++算术运算中
- 基于范围的for循环引发带有数组参数的编译器错误
- 使用 decltype for 函数生成的非类型模板参数
- 如何在 for 循环中调用参数化构造函数
- 基于范围的 for 循环是否可以采用类型参数
- 要在 for 循环中更改的模板参数
- C++ Boost::序列化"no matching function for call"到我的加载函数参数中类的构造函数
- 使用std::enableif-for-template和3个通用参数