Dmitry Kuzminov
Dmitry Kuzminov

Reputation: 6584

How to prevent implicit conversion from double to char?

There is a legacy string implementation that has an operation << to append character:

struct FancyString {
    FancyString& operator << (char c) {
        // append c to the end
        return *this;
    }
    // ...
};

Appending characters works as expected, but if someone mistakenly tries to do that with the types that can be converted the char, the behavior would be surprising.

FancyString fancyString;
fancyString << 'c'; // As expected
fancyString << 3.14; // Surprise

As I've mentioned already, this is legacy code, and unfortunately the ideal solution (deprecating this class completely) is not an option for me. I neither don't want to implement all reasonable streaming operations. The minimal pain would be to prohibit this operation for all types except characters.

How could I prevent this operation for the types other than [signed or unsigned] char? I wish the compiler to produce an error on the line where a double is being appended.

Upvotes: 0

Views: 64

Answers (1)

Pepijn Kramer
Pepijn Kramer

Reputation: 12891

If you can use C++20, this will do it:

#include <concepts>

template<typename T>
concept IsChar = std::is_same_v<T,char>;

struct FancyString 
{
    FancyString& operator<< (IsChar auto c) 
    {
        return *this;
    }
};

int main()
{
    FancyString str;
    str << 'a';
    //str << 1.23; <== this will now no longer compile
}

Upvotes: 2

Related Questions