c++ 使用泛型模板类型的变量作为另一个函数的参数

9rygscc1  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(178)

我在尝试使用模板类型来模拟C++中的泛型我有一个这样的函数

  1. template <typename ElementType1>
  2. void myFile::myFunc() {
  3. ElementType1 val = Strain() //
  4. loadNewValue(val); // this is where the problem is , "impossible to convert type ElementType1 to type Strain"

现在是loadNewValue方法:

  1. void myFile::loadNewValue(Strain strain) {
  2. //DoSomething;
  3. }

以及如何调用myFunc函数

  1. myFunc<Strain>();

和struct菌株:

  1. #pragma once
  2. #ifndef Strain_H
  3. #define Strain_H
  4. #include <iostream>
  5. using namespace std;
  6. struct Strain {
  7. int64_t ID;
  8. };
  9. #endif // Strain

我试着简化,因为我的例子要大得多
我的问题是我无法编译这些代码,因为编译器希望能够将我的泛型类型“ElementType1”转换为“Strain”,因为我将它用作loadNewValue函数的参数
我所期望的是,ElementType1的类型在运行时是已知的,并且由于在运行时它将正确地是Strain(我在注解loadNewValue时使用该类型的cout`进行了验证),因此它将只填充参数。
我尝试将瓦尔转换为“Strain”,但我得到了相同的错误,因为编译器不知道如何将ElementType1编译为Strain。
我想我一定是误解了泛型模板名的作用,因为我以为它们是在函数调用后的运行时计算的,而不是在编译时
谢谢你的帮助

dz6r00yl

dz6r00yl1#

我的问题更多的是关于为什么我的编译器期望我的泛型模板类型在编译时是“Strain”类型,而我认为模板时间在运行时被检查,以及如何避免这个问题
模板都是在编译时完成的。
对于常规的if,所有分支都应该有效。
使用if constexpr,“错误的”分支不会被示例化。
所以你可能会这样做:

  1. template <typename ElementType1>
  2. void myFile::myFunc()
  3. {
  4. ElementType1 val = funcStore() // this is a function from another library (HDFql) that automaticly "fill" val argument, this works
  5. if (std::is_same_v<Strain, type>) {
  6. loadNewValue(val);
  7. } else {
  8. loadNewValueNotStrain(val);
  9. }
  10. }

相关问题