根据参数返回类型 [英] Returning a type depending on the parameter

查看:82
本文介绍了根据参数返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个这样的函数,它的返回类型将在函数内确定(取决于参数的 value ),但是实现失败. (也许是模板专业化?)

I want to have such a function that it's return type will be decided within the function(depending on the value of the parameter), but failed implementing it. (template specialization maybe?)

// 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");
}

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

And I want to use it without specifying the type as:

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

推荐答案

这不起作用,您必须在编译时提供参数.以下将起作用:

That does not work, you would have to give the parameter at compile time. The following would work:

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,像这样:

Another version would be to pass std::integral_constant, like this:

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

这篇关于根据参数返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆