c++ - 根据参数返回类型

标签 c++ templates c++11 metaprogramming

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

// 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

关于c++ - 根据参数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30088983/

相关文章:

c++ - 使用专门的模板并命名枚举选项

C++ "error: no type named ‘type’ 在 ‘class std::result_of< ... >"

c++ - 使用迭代器列表删除 vector 中的元素?

c++ - 与 DrawText 函数冲突

c++ - Qt中如何绘制模糊的透明背景

c++ - 模板化 typedef 上的模板函数

C++ 模板化模板推导可以回避吗?

c++ - 为什么可以在 .h 接口(interface)和 .cpp 实现中拆分非模板类?

程序退出时出现 C++ 内存错误

c++ - 使用模板类特化消除代码冗余的标准方法是什么?