【问题标题】:Auto-deduce method's return type自动推断方法的返回类型
【发布时间】:2016-05-26 07:22:55
【问题描述】:

我有以下功能:

//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), 会自动推断返回类型吗?

所以,基本上,如果 getValue 被调用,它应该返回 Value&lt;FooSingle&gt;

GetValue&lt;A&gt;();

如果它被调用,它应该返回Value&lt;FooMany&gt;,例如

GetValue&lt;A, B&gt;();

GetValue&lt;A, B, C&gt;();

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

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

谢谢。

【问题讨论】:

  • 类型是一回事,但是函数中return-statement怎么写呢?

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


【解决方案1】:
#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

【讨论】:

  • 我不明白为什么会有明确的`FooAll。它应该在 FooAll 和 FooOne 之间变化,对吗?
  • 我真的不觉得这比只使用两个重载更具可读性。
猜你喜欢
  • 2011-01-13
  • 2019-10-19
  • 1970-01-01
  • 2021-06-11
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多