【问题标题】:Elegant way to return different value types from function in c++ / c++11从 c++ / c++11 中的函数返回不同值类型的优雅方法
【发布时间】:2023-03-12 02:05:01
【问题描述】:

我在堆栈溢出中寻找从 c++ 中的函数返回不同值类型的最佳方法 我发现了一些很酷的方法,尤其是这种方法尽可能接近:
C++ same function parameters with different return type

但是有问题。 值对象只能接受/转换字符串,所以如果我有这样的东西:

Value RetrieveValue(std::string key)
{
     //get value
      int value = get_value(key, etc);
      return { value };
}

我得到了:

error C2440: 'return': cannot convert from 'initializer list' to 'ReturnValue'

no suitable constructor exists to convert from "int" to "std::basic_string<char, std::char_traits<char>, std::allocator<char>>" 

我的问题是我可以修改 Value 对象以支持 bool、float 和 int 吗?

struct Value
{
    std::string _value;

    template<typename T>
    operator T() const   //implicitly convert into T
    {
       std::stringstream ss(_value);
       T convertedValue;
       if ( ss >> convertedValue ) return convertedValue;
       else throw std::runtime_error("conversion failed");
    }
}

还有为什么“值”返回:{ value }
大括号??

【问题讨论】:

  • 给定的值对象已经支持您使用隐式operator T() 列出的类型。您给出的错误消息表明您的代码与您显示的示例非常不同。如果您向我们展示您实际上尝试编译的代码,将会有所帮助。

标签: c++


【解决方案1】:

std::string 没有单独使用int 的构造函数。所以你不能直接用一个初始化std::string

您可以使用std::to_string 编译它,但是

Value RetrieveValue(std::string key)
{
     //get value
      int value = get_value(key, etc);
      return { std::to_string(value) };
}

在 cmets 中回答您的问题:

  1. {std::to_string(value)} aggregate initializes Value 对象,你的函数的返回值。

  2. 到任何T 的隐式转换发生在您的函数调用之外。当编译器需要将您返回的Value 分配给某个变量时,它会寻找适当的转换。模板化转换运算符提供的。


根据您的第二条评论。如果你只想支持基本类型,你可以放弃这个异常来支持std::is_fundamental上的static_assert

template<typename T>
operator T() const   //implicitly convert into T
{
   static_assert(std::is_fundamental<T>::value, "Support only fundamental types");
   std::stringstream ss(_value);
   T convertedValue;
   ss >> convertedValue
   return convertedValue;
}

【讨论】:

  • 谢谢,你能解释一下我不明白的两件事吗 1. 为什么返回是用大括号传递的 2. 这个//隐式转换成 T 是如何工作的 谢谢
  • 谢谢allot,你知道从函数返回不同类型的更好方法吗?
  • @user63898 - 恐怕没有绝对的。最好的方法取决于一个人想要完成什么。如果说你想避免抛出异常,并且只支持一组固定的返回类型,你可以简单地为每个你想要支持的类型 X 重载 operator X。这将产生编译时错误而不是符文时错误。但同样,这完全取决于您的应用程序的需求。
  • 重载运算符 X 是什么意思?我确实只需要固定类型的原语,所有这些字符串流到类型的转换也让我担心
  • @user63898 - 如果你只需要支持说int chardouble,那么你只重载operator intoperator charoperator double。但是你说你只想支持基本类型?让我将建议编辑到我的答案中。
猜你喜欢
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 2012-08-16
相关资源
最近更新 更多