我有两个必须是模板(C ++)的类模板。我只是简化了他们的代码以显示问题的实质。如何将一个模板(obj1
)中的对象(MyClass1
)从第二个模板(obj2
)中传递到另一个对象(MyClass2
)?我尝试通过template参数和构造函数,但是仍然有编译错误。如何正确做?重要的是,我不知道模板参数,因此解决方案具有通用性,而不适用于指定的参数。对象应该通过指针或引用传递,我不需要它的副本。
template<int a, int b>
class MyClass1 {
public:
MyClass1() {
// Do something...
}
int foo(int x) {
return a * x + b;
}
};
template<double m, double n>
class MyClass2 {
public:
MyClass2() {
// Do something
}
double bar(int x) {
// Do something with x using object of MyClass1 and then with m...
}
double zet(int x) {
// Do something with x using object of MyClass1 and then with n...
}
};
int main() {
MyClass1<4, 3> obj1;
MyClass2<3.14, 2.56> obj2; // <-- How to pass obj1 here???
// Maybe that way?: MyClass2<3.14, 2.56, obj1> obj2;
// Or that way?: MyClass2<3.14, 2.56> obj2(obj1);
obj1.foo(12);
obj2.bar(1.234);
obj2.zet(5.678);
}
我不确定这是否与此问题有关,但是我正在使用标准设置在Atmel Studio 7中为AVR编写C ++代码。
由于以下原因,您的代码无法用C ++ 11编译:
非类型模板参数必须具有结构类型,即以下类型之一(可选,具有cv资格,即限定词被忽略):
- 左值引用类型(对象或函数);
- 整数类型;
- a指针类型(指向对象或函数);
- 指向成员类型的指针(成员对象或成员函数);
- 枚举类型;
- std :: nullptr_t; (自C ++ 11起)
- 浮点类型; (自C ++ 20起)
关于您的核心问题,您可以执行以下操作:
template<int m, int n, typename Obj1Type>
class MyClass2 {
Obj1Type obj1_;
public:
MyClass2() {
// Do something
}
MyClass2(Obj1Type const& obj1) {
obj1_ = obj1;
}
// ...
};
然后是主要的:
int main() {
MyClass1<4, 3> obj1;
MyClass2<3, 2, MyClass1<4, 3>> obj2(obj1);
obj1.foo(12);
obj2.bar(1);
obj2.zet(5);
}
签出live