我在尝试使用模板类型来模拟C++中的泛型我有一个这样的函数
template <typename ElementType1>
void myFile::myFunc() {
ElementType1 val = Strain() //
loadNewValue(val); // this is where the problem is , "impossible to convert type ElementType1 to type Strain"
现在是loadNewValue方法:
void myFile::loadNewValue(Strain strain) {
//DoSomething;
}
以及如何调用myFunc函数
myFunc<Strain>();
和struct菌株:
#pragma once
#ifndef Strain_H
#define Strain_H
#include <iostream>
using namespace std;
struct Strain {
int64_t ID;
};
#endif // Strain
我试着简化,因为我的例子要大得多
我的问题是我无法编译这些代码,因为编译器希望能够将我的泛型类型“ElementType1”转换为“Strain”,因为我将它用作loadNewValue函数的参数
我所期望的是,ElementType1的类型在运行时是已知的,并且由于在运行时它将正确地是Strain(我在注解loadNewValue时使用该类型的
cout`进行了验证),因此它将只填充参数。
我尝试将瓦尔转换为“Strain”,但我得到了相同的错误,因为编译器不知道如何将ElementType1编译为Strain。
我想我一定是误解了泛型模板名的作用,因为我以为它们是在函数调用后的运行时计算的,而不是在编译时
谢谢你的帮助
1条答案
按热度按时间dz6r00yl1#
我的问题更多的是关于为什么我的编译器期望我的泛型模板类型在编译时是“Strain”类型,而我认为模板时间在运行时被检查,以及如何避免这个问题
模板都是在编译时完成的。
对于常规的
if
,所有分支都应该有效。使用
if constexpr
,“错误的”分支不会被示例化。所以你可能会这样做: