c++ - 自动推断方法的返回类型

标签 c++ c++11 type-inference

我有以下功能:

//method takes 2 or more template parameters    
template <class A1, class A2, class ...Ax>
Value<FooMany> getValue() {

    //note, FooAll's ctor takes std::string and std::initializer_list<std::size_t>

    FooAll<Item> hairyStructure("abc", { Foo<A1>::getIndex(), Foo<A2>::getIndex(), Foo<Ax>::getIndex() ... } );
    return Value<FooMany>(someData, hairyStructure);
}

//method takes only 1 template parameter
template <class A>
Value<FooSingle> getValue() {

    //note, FooOne's ctor takes std::string and std::size_t

    FooOne<Item> hairyStructure("abc", Foo<A>::getIndex() );
    return Value<FooSingle>(someData, hairyStructure);
}

.

很明显,这些函数的类型是不同的。

我想知道,是否可以将这两个压缩成一个方法,利用 C++11 特性(我想是 decltype), 会自动推断返回类型吗?

所以,基本上,它应该返回 Value<FooSingle>如果getValue被调用为

GetValue<A>();

它应该返回 Value<FooMany>如果它被调用为例如

GetValue<A, B>();

GetValue<A, B, C>();

关于“方法采用 2 个或更多模板参数”,我不确定我的术语是否正确。如有不妥请指正。

如果有帮助,我的问题继续上一个主题:C++11 parameters pack overload

谢谢。

最佳答案

#include <type_traits>

template <class A1, class... Ax>
auto getValue()
    -> Value<typename std::conditional<sizeof...(Ax) == 0
                                     , FooSingle, FooMany>::type>
{
    typename std::conditional<sizeof...(Ax) == 0
                            , FooOne<Item> 
                            , FooAll<Item>>::type
              hairyStructure("abc", { Foo<A1>::getIndex(), Foo<Ax>::getIndex()... } );
    return Value<typename std::conditional<sizeof...(Ax) == 0
                                         , FooSingle, FooMany>::type>(hairyStructure);
}

DEMO

关于c++ - 自动推断方法的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408425/

相关文章:

c++ - 在不同的行上打印 Mat 矩阵

c++ - 带有 XML 的 TCP 消息结构

c++ - 使用 enable_if 添加重载运算符 ==

c++ - 适用于集合的 std::async 变体

c++ - 具有重载运算符的自定义类在用作映射键时会导致 C2678

F# 多态类型

c++ - 如何修复 : 'undefined reference to foo()' with Makefile and g++

arrays - 为什么我不能调用reduce(到:) on an array literal in Xcode 9. 2?

Typescript:转换所有函数参数的通用函数类型

c++ - 在 C++ 中解析许多小文本的最佳解析器生成器?