Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to disable conversion operators?

Tags:

c++

Is there any way to disable the conversion operator of a class? Assume it is a library class and I cannot modify the source code (or headers). I sometimes encounter a library that thinks to be clever and defines conversions which are silly and sometimes just dangerous.

For example, given this declaration in a header which I cannot modify:

class TooClever
{
   ...
public:
   operator char const*();
};

Is there any way (trickery allowed, even if compiler specific) I can prevent this operator from ever being used in my code?

like image 929
edA-qa mort-ora-y Avatar asked Apr 22 '11 08:04

edA-qa mort-ora-y


People also ask

What is a conversion operator?

A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.

What is a conversion operator in CPP?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.

What is a conversion function How is it created explain its syntax?

Conversion function syntaxConversion functions have no arguments, and the return type is implicitly the conversion type. Conversion functions can be inherited. You can have virtual conversion functions but not static ones. Parent topic: User-defined conversions (C++ only)

How many types are there in user-defined conversion?

There are two types of user-defined conversions: Conversion constructors and conversion functions.


1 Answers

Create your own descendant, add operator char const*() to it, but make it private. While still present, this ensures it can't be called accidentally (in fact, at all).

like image 198
Frederik Slijkerman Avatar answered Oct 19 '22 18:10

Frederik Slijkerman