Liz*_*izi 4 c++ conditional templates
我想在C++中使用与模板相关的条件返回类型.我的环境中提供了C++ 11,14和17预览版.
我不是编程新手,但我是C++的新手,并且对某些功能有点困惑.
我想要实现的是:
如果模板是int32_t我的返回类型会int64_t,int16_t将返回int32_t并int8_t会返回一个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);
Run Code Online (Sandbox Code Playgroud)
我想通过只输入参数类型来使这更加实用.
int64_t x = Foo<uint32_t>(555555, 666666);
int32_t x = Foo<uint16_t>(12000, 13000;
int16_t x = Foo<uint8_t>(88, 99);
Run Code Online (Sandbox Code Playgroud)
我尝试用以下方法实现它std::conditional:
template<typename OtherType,
typename T = typename std::conditional<(sizeof(Type) <=
sizeof(OtherType)),
OtherType, Type>::type>
Run Code Online (Sandbox Code Playgroud)
我愿意使用重载和疯狂的想法.
在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...
Run Code Online (Sandbox Code Playgroud)
现在甚至不再需要返回类型的模板参数:
template <class T>
static typename foo_ret<T>::type Foo(T bar1, T bar2) {};
Run Code Online (Sandbox Code Playgroud)
您可以按照要求调用它:
int64_t x = Foo<uint32_t>(555555, 666666);
Run Code Online (Sandbox Code Playgroud)
或者让编译器推断出T你喜欢的.
| 归档时间: |
|
| 查看次数: |
778 次 |
| 最近记录: |