根据参数返回类型

6

我希望实现一个这样的函数,其返回类型将取决于函数内部传入参数的,但我无法成功实现它。(也许可以使用模板特化实现?)

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

11
函数只能有一种返回类型。C++是静态类型语言。也许你正在寻找boost::variant - chris
1
这不像是真正的代码,而更像是一个人为制造的例子。如果您能向我们展示您想要实现什么,也许我们可以提出更好的建议。 - Nasser Al-Shawwa
2
@Ausser 模板在编译期间为每个需要的类型实例化一次。auto 的类型是在编译期间推导出来的,而不是在运行时确定的。 - molbdnilo
2
也许这是一个工厂模式的尝试?你可能返回的各种类型是否有某种关联? - Kate Gregory
typeCode 是在编译时已知的还是在运行时确定的? - Nasser Al-Shawwa
显示剩余6条评论
4个回答

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

另一种版本是使用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

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

0
#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: float\n";
    return t;
}

看一下 std::enable_if 文档。可能可以用它来创建依赖于值而不仅仅是类型的返回参数类型。 - Alexander Katz

0

由于C++是面向对象的,我们可以让所有选项从一个父类继承,然后返回该父类的实例。
或者,我们可以尝试使用void*返回类型。


对不起,我不明白这与我的问题有什么关系。 - Ausser
返回不同结构化数据的两种可能方法,记住您还可以重载函数以根据传入的参数返回不同的内容。 - Joshua Byer
如果你考虑重写一个虚函数,那么你就必须使用协变返回(最多可以返回指向派生类的指针)。@JoshuaByer - vsoftco
我不会说"C++是面向对象的"。相反,它是一种多范式语言,恰好包含支持面向对象编程的特性,但完全可以编写不使用任何面向对象编程方式的C++程序。 - Jesper Juhl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接