473,785 Members | 2,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cast ambiguities

Hello,

I want to write classes, which can be used as interchangeably as
possible. The background is that they are smartpointers, which should
implicitly cast between each other.

As a toy example, let's take two classes A and B:

struct A {
A() {}
A( A const& a ) {}
};

struct B {
B() {}
B( B const& b ) {}
operator A() { return ... };

// adding either one of the two following
// lines breaks the program
// with VC++ 7.1, reason: ambiguous cast.
// Why???
// operator A const&() { return ... };
// operator A &() { return ... };
};

A func1() {
B b;
return b; // cast through B::operator A()
}

The above works, but adding either one of the two extra casts breaks
the compilation.

These casts would be useful, for example for:

func2( A const& );

func3() {
B b;
func2( b ); // reference cast here, no need to copy
}

What am I missing?

Thanks,

Arno

Sep 30 '05 #1
7 1453
Arno wrote:
Hello,

I want to write classes, which can be used as interchangeably as
possible. The background is that they are smartpointers, which should
implicitly cast between each other.

As a toy example, let's take two classes A and B:


What are the differences between class A and class B?

If they are the same in practice, class A and B should be one class.

If one is derived from the other, there should be no need to cast.

If they are not derived from each other, and not the same, then it's
not safe to use them interchangably.

Have you considered creating a base class C for both and then
inheriting A and B from C, and having it return a pointer to C? This
should allow you to do the operations you want to, but otherwise you're
dealing with a problem. Sure, you can cast a pointer value to an array
of chars, but does that make the information or valid? You have to have
a connection between the data, otherwise you have a very big chance of
running into undefined behavior.

Sep 30 '05 #2
The code above is just for demonstration. The actual code is a smart
pointer library. template< class T> Ref<T> is a smart pointer, which
should be able to implicitly cast to Ref<S> if type T is derived from
type S. In addition, Ref is implementing reference-counting.

I would be able to save some reference counts if I would not have to
create copies during casting. Ref<T> and Ref<S> must still be distinct
types, so they are type-checkable at compile time.

Sep 30 '05 #3

Arno wrote:
The code above is just for demonstration. The actual code is a smart
pointer library. template< class T> Ref<T> is a smart pointer, which
should be able to implicitly cast to Ref<S> if type T is derived from
type S. In addition, Ref is implementing reference-counting.

I would be able to save some reference counts if I would not have to
create copies during casting. Ref<T> and Ref<S> must still be distinct
types, so they are type-checkable at compile time.


Can you use a templatized constructor? Compare this code from
boost::shared_p tr:

template<class T> class shared_ptr
{
// ...
public:
template<class Y>
shared_ptr(shar ed_ptr<Y> const & r);
// ...
};

Cheers! --M

Sep 30 '05 #4
I can and I did up to now. What I do not like about it is that even
trivial casts require copying, like:

struct B {};
struct A: public B {};

func( const Ref<B>& b ) {
....
}

main() {
Ref<A> a=newObj A();
func( a );
}

Internally, Ref <> stores a simple pointer, so the binary
representations of Ref<A> and Ref<B> are identical. For the case above,
the cast could really be a no-op. But this does not work, the templated
constructor B::B() or A::operator B() is called (really no big
difference) and a copy is made, which requires some reference counting.
Reference counting is no biggie in single-threaded systems, but if you
get multithreaded and every count must be interlocked...

Sep 30 '05 #5
"Arno" <as******@thi nk-cell.com> schrieb im Newsbeitrag
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Hello,

I want to write classes, which can be used as interchangeably as
possible. The background is that they are smartpointers, which should
implicitly cast between each other.

As a toy example, let's take two classes A and B:

struct A {
A() {}
A( A const& a ) {}
};

struct B {
B() {}
B( B const& b ) {}
operator A() { return ... };

// adding either one of the two following
// lines breaks the program
// with VC++ 7.1, reason: ambiguous cast.
// Why???
// operator A const&() { return ... };
// operator A &() { return ... };
};

A func1() {
B b;
return b; // cast through B::operator A()
}

The above works, but adding either one of the two extra casts breaks
the compilation.

These casts would be useful, for example for:

func2( A const& );

func3() {
B b;
func2( b ); // reference cast here, no need to copy
}

Why don't you remove B::operator A and add operator A& or operator A const&
instead. You can almost(?) allways use a const ref where a value is
required.

HTH
Heinz
Oct 1 '05 #6
Yes, so I thought. But it does not work when casting return values!

A func() {
B b;
return b;
}

only compiles if there is a B::operator A() or a A::A(const B&). If
there is only a B::operator A&() or B::operator A const&() the compiler
complains of having to do two casts for "return b" in the function
above. And if B::operator A() exists in addition, it complains about
ambiguity... I just don't understand the rules well enough...

Arno

Oct 1 '05 #7
* Arno:
I can and I did up to now. What I do not like about it is that even
trivial casts require copying, like:

struct B {};
struct A: public B {};

func( const Ref<B>& b ) {
...
}

main() {
Ref<A> a=newObj A();
func( a );
}

Internally, Ref <> stores a simple pointer, so the binary
representations of Ref<A> and Ref<B> are identical. For the case above,
the cast could really be a no-op. But this does not work, the templated
constructor B::B() or A::operator B() is called (really no big
difference) and a copy is made, which requires some reference counting.
Reference counting is no biggie in single-threaded systems, but if you
get multithreaded and every count must be interlocked...


Let's use the names Base and Derived instead of B and A.

If the Ref smart pointer class is re-seatable (i.e. you can make a Ref point
to something new after initialization) , then Ref<Derived> should not behave as
if derived from Ref<Base>, because if it did, then you could erronously make a
Ref<Derived> point to a Base instance. Isn't it great that the language, in
practice, prevents that error? And thus shows you what goes on behind the
scenes in languages with transparent re-seatable object references.

That said, in some other contexts there is a need for wrapping a hierarchy of
classes in a parallell hierarchy, and this is a largely unsolved problem in
the sense that one must employ case-specific trade offs: no general solution.
And this is the problem when Ref is not re-seatable. Without cranking my
hind-brain too much I think the closest one can come to a general solution, in
C++, is virtual inheritance from a pure interface hierarchy, which is a bit
awkward in that it introduces a third parallell class hierarchy, and it also
introduces an inefficiency that may or may not be significant (I'm not sure).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 1 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
6025
by: Jordi Vilar | last post by:
Hi All, Is there a way to dynamic_cast a pointer to a type defined by a type_info*? something like: type_info *info_of_type_to_cast = typeid(type_to_cast); type_to_cast *casted = really_dynamic_cast<info_of_type_to_cast>(my_data_ptr);
0
3595
by: Aaron W. West | last post by:
Fun with CAST! (Optimized SQLServerCentral script posts) I found some interesting "tricks" to convert binary to hexadecimal and back, which allow doing 4 or 8 at a time. Test code first: -- These two have the same output, other than the width: select dbo.ufn_vbintohexstr(0x123456789abcdef1234) select 0x123456789abcdef1234
4
10472
by: Ray | last post by:
When a single-bit bitfield that was formed from an enum is promoted/cast into an integer, does ANSI C say anything about whether that integer should be signed or unsigned? SGI IRIX cc thinks it is an unsigned integer, so I see a +1 if the bit is set. Microsoft VC++ thinks it's signed, so I see -1 if the bit is set. Ex. typedef enum {
17
2677
by: Hazz | last post by:
In this sample code of ownerdraw drawmode, why does the '(ComboBox) sender' line of code need to be there in this event handler? Isn't cboFont passed via the managed heap, not the stack, into this cboFont_DrawItem event handler? Why does it need to be cast? -hazz ,................. cboFont.Items.AddRange(FontFamily.Families); } private void cboFont_DrawItem(object sender,
5
3437
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to provide some common functionality. The Page_Load handler the failing webpage starts out like this: ...
6
6729
by: Lore Leunoeg | last post by:
Hello I derived a class MyControl from the Control class. Public Class MyControl Inherits Control Sub New() MyBase.New() End Sub End Class
9
2726
by: Frederick Gotham | last post by:
Let's assume that we're working on the following system: CHAR_BIT == 8 sizeof( char* ) == 4 (i.e. 32-Bit) Furthermore, lets assume that the memory addresses are distributed as follows: 0x00000000 through 0xFFFFFFFE : Valid byte addresses
5
2367
by: Frederick Gotham | last post by:
Before I begin, here's a list of assumptions for this particular example: (1) unsigned int has no padding bits, and therefore no invalid bit- patterns or trap representations. (2) All types have the same alignment requirements. (3) sizeof(double) >= sizeof(unsigned) ===================================== We can cast from double to unsigned int as follows:
8
2200
by: junky_fellow | last post by:
Hi, Sorry, for asking similar questions again and again. 1) I want to know how should we reslove the ambiguities in a c expression ? Should we use precedence table as mentioned in K&R book or should we refer to the ANSI C grammar ? 2) As told by many people in this newsgroup that ANSI C grammar does
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9483
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10346
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8982
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.