C ++自动推断返回类型 [英] C++ auto deduction of return type

查看:60
本文介绍了C ++自动推断返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,根据不同的输入返回不同的类型,如下所示.

I want to write a function that return different types based on different input as below.

enum MyType
{
    A,
    B
};

template<MyType T> struct MyStruct
{

};

static auto createMyStruct(MyType t)
{
    if(t==A)
        return MyStruct<A>();
    else
        return MyStruct<B>();
}

之所以无法解决,是因为一种汽车有两种返回类型.还有其他方法吗?

It didn't work out because there are two return types for one auto. Is there any other way to do this?

推荐答案

绝对没有办法让(单个)函数根据运行时决策返回不同的类型.返回类型必须在编译时知道.但是,您可以使用这样的模板函数(感谢@dyp使我简化了代码):

There is absolutely no way of having a (single) function that returns different types based on a runtime decision. The return type has to be known at compile time. However, you can use a template function, like this (thanks to @dyp for making me simplify the code):

#include <iostream>
#include <typeinfo>

enum MyType
{
    A,
    B
};

template<MyType>
struct MyStruct {};

template<MyType type>
MyStruct<type> createMyStruct()
{
    return {};
}

int main()
{
    auto structA = createMyStruct<A>();
    auto structB = createMyStruct<B>();

    std::cout << typeid(structA).name() << std::endl;
    std::cout << typeid(structB).name() << std::endl;
}

这篇关于C ++自动推断返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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