自动推断方法的 return 类型
Auto-deduce method's return type
我有以下功能:
//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),
会自动推断出 return 类型吗?
所以,基本上,它应该 return Value<FooSingle>
如果 getValue
被调用为
GetValue<A>();
并且它应该 return Value<FooMany>
如果它被调用例如
GetValue<A, B>();
或
GetValue<A, B, C>();
我不确定关于 "method takes 2 or more template parameters" 我的术语是否正确。如有不妥请指正
如果有帮助,我的问题继续上一个主题:
谢谢。
#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);
}
我有以下功能:
//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), 会自动推断出 return 类型吗?
所以,基本上,它应该 return Value<FooSingle>
如果 getValue
被调用为
GetValue<A>();
并且它应该 return Value<FooMany>
如果它被调用例如
GetValue<A, B>();
或
GetValue<A, B, C>();
我不确定关于 "method takes 2 or more template parameters" 我的术语是否正确。如有不妥请指正
如果有帮助,我的问题继续上一个主题:
谢谢。
#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);
}