根据参数返回类型

Returning a type depending on the parameter

本文关键字:返回类型 参数      更新时间:2023-10-16

我想具有这样的函数,以至于它的返回类型将在函数中确定(取决于参数的 value ),但未能实现它。(也许模板专业化?)

// 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 :: integnal_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 是面向对象的,我们可以从父类中继承所有选项,然后返回该父类的实例。
另外,我们可以尝试void *返回类型。

#include <type_traits>
#include <iostream>
// foo1 overloads are enabled via the return type
template<class T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type 
foo1(T t) 
{
    std::cout << "foo1: floatn";
    return t;
}

来自C 17,也可以使用if constexpr在问题中保留与代码相似的结构:

template<int typeCode>
auto GetVar()
{
  if constexpr(typeCode == 0) return int(0);
  else if constexpr(typeCode == 1) return double(0);
  else return std::string("string");
}