加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 根据参数返回类型

发布时间:2020-12-16 07:12:07 所属栏目:百科 来源:网络整理
导读:我希望有这样一个函数,它的返回类型将在函数内决定(取决于参数的值),但实现失败. (模板专业化可能吗?) // half-pseudo codeauto GetVar(int typeCode){ if(typeCode == 0)return int(0); else if(typeCode == 1)return double(0); else return std::string(
我希望有这样一个函数,它的返回类型将在函数内决定(取决于参数的值),但实现失败. (模板专业化可能吗?)

// half-pseudo code
auto GetVar(int typeCode)
{
  if(typeCode == 0)return int(0);
  else if(typeCode == 1)return double(0);
  else return std::string("string");
}

我想在不指定类型的情况下使用它:

auto val = GetVar(42); // val's type is std::string

解决方法

这不起作用,你必须在编译时给出参数.以下将有效:

template<int Value>
double GetVar() {return 0.0;};

template<>
int GetVar<42>() {return 42;}

auto x = GetVar<0>(); //type(x) == double
auto y = GetVar<42>(); //type(x) == int

另一个版本是传递std :: integral_constant,如下所示:

template<int Value>
using v = std::integral_constant<int,Value>;

template<typename T>
double GetVar(T) {return 0;};

int GetVar(v<42>) {return 42;};

auto x = GetVar(v<0>()); //type(x) == double
auto y = GetVar(v<42>()); //type(x) == int

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读