c++ - 如何将模板的实例传递给另一个模板的另一个实例?

标签 c++ templates avr atmega atmelstudio

我有两个类模板,它们必须是模板 (C++)。我只是简化了他们的代码以展示问题的本质。如何将一个对象 (obj1) 从一个模板 (MyClass1) 传递到第二个模板 (MyClass2<) 中的另一个对象 (obj2)/)?我尝试了模板参数和构造函数,但仍然出现编译错误。怎样做才正确呢?重要的是,我不知道模板参数,因此解决方案是通用的,而不是针对指定的参数。对象应该通过指针或引用传递,我不需要它的拷贝。

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 进行编译:

A non-type template parameter must have a structural type, which is one of the following types (optionally cv-qualified, the qualifiers are ignored):

  • lvalue reference type (to object or to function);
  • an integral type;
  • a pointer type (to object or to function);
  • a pointer to member type (to member object or to member function);
  • an enumeration type;
  • std::nullptr_t; (since C++11)
  • a floating-point type; (since C++20)

关于你的核心问题,你可以这样做:

template<int m, int n, typename Obj1Type>
class MyClass2 {
    Obj1Type obj1_;

public:
    MyClass2() {
        // Do something
    }

    MyClass2(Obj1Type const& obj1) {
        obj1_ = obj1;
    }

    // ...
};

然后在main中:

int main() {
    MyClass1<4, 3> obj1;
    MyClass2<3, 2, MyClass1<4, 3>> obj2(obj1);

    obj1.foo(12);
    obj2.bar(1);
    obj2.zet(5);
}

查看一下 live

更新

您还可以利用继承并为此目的创建一个简单的基类:

class BaseMyClass1 {};

template<int a, int b>
class MyClass1 : public BaseMyClass1 {
    // ...
};

template<int m, int n>
class MyClass2 {
    BaseMyClass1 obj1_;

public:
    MyClass2() {
        // Do something
    }

    template <typename Obj1Type>
    MyClass2(Obj1Type const& obj1) {
        obj1_ = obj1;
    }

    // ...
};

然后在main中:

int main() {
    MyClass1<4, 3> obj1;
    MyClass2<3, 2> obj2(obj1);

    obj1.foo(12);
    obj2.bar(1);
    obj2.zet(5);
}

这可以节省您在模板参数列表中声明模板的麻烦。但是,这可能不是您的完美解决方案,因为它引入了对象切片。

查看一下 live

关于c++ - 如何将模板的实例传递给另一个模板的另一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164663/

相关文章:

c++ - 如何从 E_FAIL 获取详细的错误信息?

c++ - 如何将单个char转换为int

c++ - 类型检查模板参数导致的编译器错误

css - MailChimp 白色文本模板问题

angular - 我怎样才能从 Angular 4 中的 *ngFor 循环中断?

c - 使用树莓派将 .hex 文件从 ArduinoIDe 上传到 attiny85

c - C 无法识别 AVR USART 文件

c++ - c/c++ 和 objective c ios

C++ 将特殊的 ascii 字符打印到 Windows 控制台

c++ - C++ 中使用什么类型来定义数组大小?