带模板的条件 return 类型
Conditional return type with template
我想在 C++ 中使用与模板相关的条件 return 类型。
C++ 11、14 和 17 预览版 在我的环境中可用。
我不是编程新手,但我是 C++ 新手,对某些功能有点困惑。
我想要实现的是:
如果模板是 int32_t
,我的 return 类型将是 int64_t
,int16_t
将 return 一个 int32_t
和 int8_t
将 return 一个 int16_t
.
实际上我正在为两者使用通用模板:
template <class T, class T2>
static T2 Foo(T bar1, T bar2) { //do something }
int64_t x = Foo<uint32_t, uint64_t>(555555, 666666);
我想通过只输入参数类型来使它更实用一些。
int64_t x = Foo<uint32_t>(555555, 666666);
int32_t x = Foo<uint16_t>(12000, 13000;
int16_t x = Foo<uint8_t>(88, 99);
我尝试用std::conditional
实现它:
template<typename OtherType,
typename T = typename std::conditional<(sizeof(Type) <=
sizeof(OtherType)),
OtherType, Type>::type>
我愿意使用重载和疯狂的想法。
在 C++ 中,一种惯用的方法是使用特征。
例如:
template<typename> struct foo_ret;
template<> struct foo_ret<uint32_t> { using type = uint64_t; };
template<> struct foo_ret<uint16_t> { using type = uint32_t; };
// And so on...
现在甚至不再需要 return 类型的模板参数:
template <class T>
static typename foo_ret<T>::type Foo(T bar1, T bar2) {};
您可以按照要求按如下方式调用它:
int64_t x = Foo<uint32_t>(555555, 666666);
或者让编译器推断 T
如果您愿意。
您可以尝试使用编译时映射来获得您想要的 return 类型
typedef boost::mpl::map<
boost::mpl::pair<uint32_t,uint64_t>,
boost::mpl::pair<uint16_t,uint32_t>,
boost::mpl::pair<uint8_t,uint16_t>
> type_map_t;
template <typename T>
typename boost::mpl::at<type_map_t,T>::type Foo(T bar1, T bar2) {}
我想在 C++ 中使用与模板相关的条件 return 类型。 C++ 11、14 和 17 预览版 在我的环境中可用。
我不是编程新手,但我是 C++ 新手,对某些功能有点困惑。
我想要实现的是:
如果模板是 int32_t
,我的 return 类型将是 int64_t
,int16_t
将 return 一个 int32_t
和 int8_t
将 return 一个 int16_t
.
实际上我正在为两者使用通用模板:
template <class T, class T2>
static T2 Foo(T bar1, T bar2) { //do something }
int64_t x = Foo<uint32_t, uint64_t>(555555, 666666);
我想通过只输入参数类型来使它更实用一些。
int64_t x = Foo<uint32_t>(555555, 666666);
int32_t x = Foo<uint16_t>(12000, 13000;
int16_t x = Foo<uint8_t>(88, 99);
我尝试用std::conditional
实现它:
template<typename OtherType,
typename T = typename std::conditional<(sizeof(Type) <=
sizeof(OtherType)),
OtherType, Type>::type>
我愿意使用重载和疯狂的想法。
在 C++ 中,一种惯用的方法是使用特征。
例如:
template<typename> struct foo_ret;
template<> struct foo_ret<uint32_t> { using type = uint64_t; };
template<> struct foo_ret<uint16_t> { using type = uint32_t; };
// And so on...
现在甚至不再需要 return 类型的模板参数:
template <class T>
static typename foo_ret<T>::type Foo(T bar1, T bar2) {};
您可以按照要求按如下方式调用它:
int64_t x = Foo<uint32_t>(555555, 666666);
或者让编译器推断 T
如果您愿意。
您可以尝试使用编译时映射来获得您想要的 return 类型
typedef boost::mpl::map<
boost::mpl::pair<uint32_t,uint64_t>,
boost::mpl::pair<uint16_t,uint32_t>,
boost::mpl::pair<uint8_t,uint16_t>
> type_map_t;
template <typename T>
typename boost::mpl::at<type_map_t,T>::type Foo(T bar1, T bar2) {}