c – 根据参数返回类型

c – 根据参数返回类型,第1张

概述我希望有这样一个函数,它的返回类型将在函数内决定(取决于参数的值),但实现失败. (模板专业化可能吗?) // half-pseudo codeauto GetVar(int typeCode){ if(typeCode == 0)return int(0); else if(typeCode == 1)return double(0); else return std::stri 我希望有这样一个函数,它的返回类型将在函数内决定(取决于参数的值),但实现失败. (模板专业化可能吗?)

// half-pseudo codeauto 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) == doubleauto 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) == doubleauto y = Getvar(v<42>()); //type(x) == int
总结

以上是内存溢出为你收集整理的c – 根据参数返回类型全部内容,希望文章能够帮你解决c – 根据参数返回类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1227638.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存