On Sat, Feb 20, 2016 at 10:35:06AM +0000, Jonathan Wakely wrote:
On 20/02/16 03:32 +0000, Jonathan Wakely wrote:
>On 19/02/16 20:18 -0700, Orion Poplawski wrote:
>>octave has template functions that call abs() on templated
>>variables, something like:
>>
>>template <class T>
>>T myfunc(T arg) {
>>T x = abs(arg);
>>}
>>
>>
>>This leads to errors when instantiated for unsigned types
>>because abs(unsigned type) is not defined as is doesn't make
>>sense to do.
>>That's fine and all, but how then does one write generic
>>template code as above that works for signed and unsigned types.
>
>
>template <class T>
>typename std::enable_if<std::is_signed<T>::value, T>::type
>generic_abs(T arg) {
> return abs(arg);
>}
>
>template <class T>
>typename std::enable_if<!std::is_signed<T>::value, T>::type
>generic_abs(T arg) {
> return arg;
>}
>
>template <class T>
>T myfunc(T arg) {
> T x = generic_abs(arg);
>}
Or maybe better, figure out which version of abs() it used to call
before the GCC 6 changes, which was probably abs(int), and just cast
to that.
If it worked before without an overloaded abs() then implicitly
converting to int must have been OK (or a lurking bug). So just:
template <class T>
T myfunc(T arg) {
T x = abs((int)arg);
}
Or define
unsigned abs(unsigned x) { return x; } ?
Zbyszek