我有以下功能:
//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);
}
关于c++ - 自动推断方法的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408425/