1

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?

misev
  • 349
  • 3
  • 11

1 Answers1

2

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)};
darune
  • 10,480
  • 2
  • 24
  • 62