我有以下代码:
helper.hpp:
struct A {
uint32_t a, b;
};
struct B {
uint32_t a, b;
};
template <typename T>
struct C {
T barcode;
};
Run Code Online (Sandbox Code Playgroud)
现在基于某些条件我想在main.cpp中创建适当的struct对象
if(/* something */) {
C<A> obj;
}
else {
C<B> obj;
}
Run Code Online (Sandbox Code Playgroud)
现在问题是因为它在if范围内我无法访问它.处理它的一种方法是从函数返回对象,如下所示:
template <typename T>
C<T> getObject(){
if(/* something */) {
return C<A>{};
}
else{
return C<B>{};
}
}
auto obj = getObject()
Run Code Online (Sandbox Code Playgroud)
但这给了我以下编译错误:
错误:没有用于调用'getObject()注释的匹配函数:无法推导出模板参数'T'
真的很感激任何帮助.