[英]Making function template parameter unsigned in C++11
In a template function that looks like this: 在模板函数中,如下所示:
template<typename T> constexpr T foo(T a, T b) { return /*recursive call*/; }
I am getting a warning about comparing signed vs unsigned (due to comparing against sizeof
) which I'd like to eliminate. 我收到一个关于比较已签名与未签名(由于与
sizeof
进行比较)的警告,我想删除它。
Conceptually, one would need something like this: 从概念上讲,人们需要这样的东西:
template<typename T> constexpr T foo(T a, unsigned T b) { ... }
or
template<typename T> constexpr T foo(T a, std::make_unsigned<T>::type b) { ... }
Unluckily, the first version is not valid C++, and the second version breaks the build because T is not a qualified type when the compiler sees make_unsigned
. 不幸的是,第一个版本不是有效的C ++,第二个版本打破了构建,因为当编译器看到
make_unsigned
时T不是限定类型。
Is there is a solution for this that actually works? 是否有解决方案实际上有效?
(NB: Somehow related to / almost same as Get the signed/unsigned variant of an integer template parameter without explicit traits , though function rather than class (so no typedefs), traits or any feature of C++11 explicitly welcome, and working solution (ie not make_unsigned<T>
) preferred.) (注意:以某种方式与获取整数模板参数的有符号/无符号变体没有显式特征相关/几乎相同,虽然函数而不是类(因此没有typedef),特征或C ++ 11的任何特性明确欢迎,并且正在工作解决方案(即不是
make_unsigned<T>
)首选。)
You forgot a 'typename' 你忘记了'typename'
template<typename T>
constexpr T foo(T a, typename std::make_unsigned<T>::type b) { ... }
In C++14 you should be able to write 在C ++ 14中,您应该能够编写
template<typename T>
constexpr T foo(T a, std::make_unsigned_t<T> b) { ... }
Or you can implement this yourself in C++11: 或者您可以在C ++ 11中自己实现:
template<typename T>
using make_unsigned_t = typename std::make_unsigned<T>::type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.