How to prevent implicit conversion from int to unsigned int?

Viewed 4663

Suppose you have this:

struct Foo {
    Foo(unsigned int x) : x(x) {}
    unsigned int x;
};

int main() {
    Foo f = Foo(-1);     // how to get a compiler error here?
    std::cout << f.x << std::endl;
}

Is it possible to prevent the implicit conversion?

The only way I could think of is to explicilty provide a constructor that takes an int and generates some kind of runtime error if the int is negative, but it would be nicer if I could get a compiler error for this.

I am almost sure, that there is a duplicate, but the closest I could find is this question which rather asks why the implicit conversion is allowed.

I am interested in both, C++11 and pre C++11 solutions, preferably one that would work in both.

3 Answers
Related