misev
misev

Reputation: 359

casting unsigned to complex<int> causes sign-conversion warning

Consider the following code:

#include <complex>

int main()
{
    unsigned u = 1u;
    auto result = static_cast<std::complex<int>>(u);
    return 0;
}

Compiling with

g++ -std=c++11 -Werror -Wsign-conversion -o a.out source_file.cpp

Causes compile error

source_file.cpp: In function ‘int main()’:
source_file.cpp:8:51: error: conversion to ‘int’ from ‘unsigned int’ may change the sign of the result [-Werror=sign-conversion]
     auto result = static_cast<std::complex<int>>(u);
                                                   ^

clang reports a similar error

source_file.cpp:6:50: error: implicit conversion changes signedness: 'unsigned int' to 'const value_type' (aka 'const int') [-Werror,-Wsign-conversion]
    auto result = static_cast<std::complex<int>>(u);
                  ~~~~~~~~~~~                    ^

The error does not make much sense at first sight, what am I missing?

Upvotes: 1

Views: 311

Answers (1)

darune
darune

Reputation: 11150

You get a conversion warning not from the cast, but from inside construction of std::complex.

To 'fix' your example you should instead do:

auto result = std::complex<int>{static_cast<int>(u)};

Upvotes: 2

Related Questions