根据参数返回类型

Aus*_*ser 5 c++ templates metaprogramming c++11

我想要一个函数,它的返回类型将在函数内决定(取决于参数的),但未能实现它。(可能是模板专业化?)

// 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");
}
Run Code Online (Sandbox Code Playgroud)

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

auto val = GetVar(42); // val's type is std::string
Run Code Online (Sandbox Code Playgroud)

Kle*_*ern 2

这不起作用,您必须在编译时给出参数。以下内容将起作用:

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
Run Code Online (Sandbox Code Playgroud)

另一个版本是传递 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
Run Code Online (Sandbox Code Playgroud)