【问题标题】:Returning a type depending on the parameter根据参数返回类型
【发布时间】:2015-05-06 22:45:22
【问题描述】:

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

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

【问题讨论】:

  • 函数只能有一种返回类型。 C++ 是静态类型的。也许你正在寻找boost::variant
  • @chris:模板函数、自动函数怎么样?
  • 这看起来不像真正的代码,而是一个人为的例子。如果您可以向我们展示您想要达到的目标,也许我们可以提出更好的建议
  • @Ausser 模板为编译期间需要的每种类型实例化一次。 auto的类型是在编译时推导出来的,不是在运行时确定的。
  • 也许这是对工厂模式的尝试?您可能返回的各种类型是否以某种方式相关?

标签: c++ templates c++11 metaprogramming


【解决方案1】:

这不起作用,您必须在编译时提供参数。以下将起作用:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 对不起,我不明白这与我的问题有什么关系。
    • 两种可能的方法来返回不同的结构化数据,请记住,您还可以重载函数以根据传入的参数返回不同的东西
    • @JoshuaByer 如果您考虑重写一个虚函数,那么您会遇到协变返回(最多可以返回一个指向派生类的指针)。
    【解决方案3】:
    #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 文档。可能您可以使用它来创建取决于值而不仅仅是类型的返回参数类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2018-04-30
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多