小编Avi*_*Avi的帖子

根据条件从函数模板返回不同的类型

我有以下代码:

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'

真的很感激任何帮助.

c++ templates c++11

3
推荐指数
2
解决办法
1824
查看次数

标签 统计

c++ ×1

c++11 ×1

templates ×1