I am working on an outdated library that needs to be backward compatible with C ++ 03, but also compatible with Outlook, to use the features of C ++ 11, such as transfer semantics and explicit casting.
So, is it possible to emulate explicit casting in C ++ 03? I obviously know about the explicit bool (or "safe" bool) idiom, but this is only for casting for the boolean type. Is it possible to emulate a common explicit casting operator in C ++ 03?
I checked and found a discussion about this in a book entitled "Imperfect C ++: Practical Solutions for Real Programming . "
In this book, they discuss some ideas about emulating explicit casts in C ++ 03 (the book was written before C ++ 11). Ultimately, it is recommended that you create a template explicit_cast<T>. However, I do not like this solution because I want users to just be able to use static_cast<T>one that works fine in C ++ 11.
So, another solution was to get the compiler to do two conversions that would forbid implicit conversions. An example of this might be something like:
class int_cast
{
public:
int_cast(const int& v) : m_value(v)
{ }
operator int() const
{
return m_value;
}
private:
int m_value;
};
struct Foo
{
Foo()
{
x = 10;
}
operator int_cast() const
{
return int_cast(x);
}
int x;
};
Here it Fooshould be explicitly converted to int, but implicitly. (This code comes almost verbatim from Imperfect C ++, except in their example they convert the user object Timeto std::tm.
However, this does not actually work, at least not using GCC 4.7.2:
Foo f;
int x = static_cast<int>(f);
It leads to:
test3.cpp: In function ‘int main()’:
test3.cpp:44:28: error: invalid static_cast from type ‘Foo’ to type ‘int’
, , "Imperfect ++" . Foo int, . ( , ?) , ++ 03 ( )?