工厂函数返回元组的C++11模式

C++11 pattern for factory function returning tuple

本文关键字:C++11 模式 元组 函数 返回 工厂      更新时间:2023-10-16

在我的项目中,我有一些函数,例如

std::tuple<VAO, Mesh, ShaderProgram> LoadWavefront(std::string filename);

我可以这样使用:

VAO teapotVAO;
Mesh teapotMesh;
ShaderProgram teapotShader;
std::tie(teapotVAO, teapotMesh, teapotShader)
    = LoadWavefront("assets/teapot.obj");
问题是,这

要求这些类中的每一个都有一个默认构造函数,该构造函数在无效状态下创建它们,这很容易出错。如何在不必std::get<>每个项目的情况下解决这个问题?有没有一种优雅的方法可以做到这一点?

有一种倒置控制流样式可能很有用。

LoadWavefront("assets/teapot.obj", [&]( VAO teapotVAO, Mesh teapotMesh, ShaderProgram teapotShader ){
  // code
});

使用VAO&引用样式而不是可选。 在这种情况下,lambda 的返回值可以用作LoadWavefront的返回值,默认的 lambda 只是转发所有 3 个参数,如果需要,允许"旧式"访问。 如果你只想要一个,或者想在加载后做一些事情,你也可以这样做。

现在,LoadWavefront可能应该返回一个future,因为它是一个 IO 函数。 在这种情况下,future tuple . 我们可以使上面的模式更通用一些:

template<class... Ts, class F>
auto unpack( std::tuple<Ts...>&& tup, F&& f ); // magic

并做

unpack( LoadWavefront("assets/teapot.obj"), [&]( VAO teapotVAO, Mesh teapotMesh, ShaderProgram teapotShader ){
  // code
});

unpack也可以被教导std::future,并自动创造结果的未来。

这可能会导致一些烦人的括号级别。 如果我们想疯了,我们可以从函数式编程中窃取一个页面:

LoadWavefront("assets/teapot.obj")
*sync_next* [&]( VAO teapotVAO, Mesh teapotMesh, ShaderProgram teapotShader ){
  // code
};

其中LoadWavefront返回一个std::future<std::tuple>。 命名运算符*sync_next*在左侧获取一个std::future,在右侧获取一个 lambda,协商调用约定(首先尝试平展tuple s),并将future作为延迟调用继续。 (请注意,在 Windows 上,async返回的std::future无法在销毁时.wait(),这违反了标准)。

然而,这是一种疯狂的方法。 可能会有更多这样的代码随着建议的await而下降,但它将提供更干净的语法来处理它。


无论如何,这里是中缀*then*命名运算符的完整实现,只是因为现场示例

#include <utility>
#include <tuple>
#include <iostream>
#include <future>
// a better std::result_of:
template<class Sig,class=void>
struct invoke_result {};
template<class F, class... Args>
struct invoke_result<F(Args...), decltype(void(std::declval<F>()(std::declval<Args>()...)))>
{
  using type = decltype(std::declval<F>()(std::declval<Args>()...));
};
template<class Sig>
using invoke_t = typename invoke_result<Sig>::type;
// complete named operator library in about a dozen lines of code:
namespace named_operator {
  template<class D>struct make_operator{};
  template<class T, class O> struct half_apply { T&& lhs; };
  template<class Lhs, class Op>
  half_apply<Lhs, Op> operator*( Lhs&& lhs, make_operator<Op> ) {
      return {std::forward<Lhs>(lhs)};
  }
  template<class Lhs, class Op, class Rhs>
  auto operator*( half_apply<Lhs, Op>&& lhs, Rhs&& rhs )
  -> decltype( invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ) )
  {
      return invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
  }
}
// create a named operator then:
static struct then_t:named_operator::make_operator<then_t> {} then;
namespace details {
  template<size_t...Is, class Tup, class F>
  auto invoke_helper( std::index_sequence<Is...>, Tup&& tup, F&& f )
  -> invoke_t<F(typename std::tuple_element<Is,Tup>::type...)>
  {
      return std::forward<F>(f)( std::get<Is>(std::forward<Tup>(tup))... );
  }
}
// first overload of A *then* B handles tuple and tuple-like return values:
template<class Tup, class F>
auto invoke( Tup&& tup, then_t, F&& f )
-> decltype( details::invoke_helper( std::make_index_sequence< std::tuple_size<std::decay_t<Tup>>{} >{}, std::forward<Tup>(tup), std::forward<F>(f) ) )
{
  return details::invoke_helper( std::make_index_sequence< std::tuple_size<std::decay_t<Tup>>{} >{}, std::forward<Tup>(tup), std::forward<F>(f) );
}
// second overload of A *then* B
// only applies if above does not:
template<class T, class F>
auto invoke( T&& t, then_t, F&& f, ... )
-> invoke_t< F(T) >
{
  return std::forward<F>(f)(std::forward<T>(t));
}
// support for std::future *then* lambda, optional really.
// note it is defined recursively, so a std::future< std::tuple >
// will auto-unpack into a multi-argument lambda:
template<class X, class F>
auto invoke( std::future<X> x, then_t, F&& f )
-> std::future< decltype( std::move(x).get() *then* std::declval<F>() ) >
{
  return std::async( std::launch::async,
    [x = std::move(x), f = std::forward<F>(f)]() mutable {
      return std::move(x).get() *then* std::move(f);
    }
  );
}
int main()
{
  7
  *then* [](int x){ std::cout << x << "n"; };
  std::make_tuple( 3, 2 )
  *then* [](int x, int y){ std::cout << x << "," << y << "n"; };
  std::future<void> later =
    std::async( std::launch::async, []{ return 42; } )
    *then* [](int x){ return x/2; }
    *then* [](int x){ std::cout << x << "n"; };
  later.wait();
}

这将允许您执行以下操作:

LoadWaveFront("assets/teapot.obj")
*then* [&]( VAO teapotVAO, Mesh teapotMesh, ShaderProgram teapotShader ){
  // code
}

我觉得很可爱。

我如何在不必 std::get<> 每个项目的情况下解决这个问题?有没有一种优雅的方法可以做到这一点?

按值返回

,而不是按"值"返回(这是这个 std::tuple 允许你做的)。

接口更改:

class Wavefront
{
public:
    Wavefront(VAO v, Mesh m, ShaderProgram sp); // use whatever construction
                                                // suits you here; you will
                                                // only use it internally
                                                // in the load function, anyway
    const VAO& vao() const;
    const Mesh& mesh() const;
    const ShaderProgram& shader() const;
};
Wavefront LoadWavefront(std::string filename);
您可以使用

boost::optional

boost::optional<VAO> teapotVAO;
boost::optional<Mesh> teapotMesh;
boost::optional<ShaderProgram> teapotShader;
std::tie(teapotVAO, teapotMesh, teapotShader)
    = LoadWavefront("assets/teapot.obj");

当然,您必须更改访问这些值的方式以始终执行*teapotVAO,但至少编译器会在您弄乱任何访问时通知您。

让我们更进一步,假设这些类没有默认构造函数。

一种选择是这样的:

auto tup = LoadWavefront("assets/teapot.obj");
VAO teapotVAO(std::move(std::get<0>(tup)));
Mesh teapotMesh(std::move(std::get<1>(tup)));
ShaderProgram teapotShader(std::move(std::get<2>(tup)));

仍然使tup周围大部分被清理干净,这不太理想。

但是等等...为什么那些甚至需要拥有所有权?

auto tup = LoadWavefront("assets/teapot.obj");
VAO& teapotVAO=std::get<0>(tup);
Mesh& teapotMesh=std::get<1>(tup);
ShaderProgram& teapotShader=std::get<2>(tup);

只要引用与返回的元组位于同一范围内,这里就没有问题。

就个人而言,这似乎是一个明确的地方,人们应该使用一组智能指针而不是胡说八道:

LoadWavefront(const char*,std::unique_ptr<VAO>&,std::unique_ptr<Mesh>&,std::unique_ptr<ShaderProgram>&);
std::unique_ptr<VAO> teapotVAO;
std::unique_ptr<Mesh> teapotMesh;
std::unique_ptr<ShaderProgram> teapotShader;
LoadWavefront("assets/teapot.obj",teapotVAO,teapotMesh,teapotShader);

这将解决所有权问题并允许合理的空状态。

编辑:/u/dyp 指出您可以将以下内容与原始输出样式一起使用

std::unique_ptr<VAO> teapotVAO;
std::unique_ptr<Mesh> teapotMesh;
std::unique_ptr<ShaderProgram> teapotShader;
std::tie(teapotVAO,teapotMesh,teapotShader) = LoadWavefront("assets/teapot.obj");