C ++ 11模式用于返回元组的工厂函数 [英] C++11 pattern for factory function returning tuple

查看:198
本文介绍了C ++ 11模式用于返回元组的工厂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my project I have some functions like

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<> 每个项目?有没有一个优雅的方法来做到这一点?

The problem is, this requires each of those classes to have a default constructor that creates them in an invalid state, which is error prone. How do I get around that without having to std::get<> each item? Is there an elegant way to do this?

推荐答案


std :: get<>每个项目?是否有一个优雅的方法来做到这一点?

How do I get around that without having to std::get<> each item? Is there an elegant way to do this?

返回值,而不是返回值这是什么std: :tuple允许你这样做。)

Return by value, instead of returning by "values" (which is what this std::tuple allows you to do).

API更改:

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);

这篇关于C ++ 11模式用于返回元组的工厂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆