473,787 Members | 2,931 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

implicit_cast isn't possible... is it?

Given the following:

static_cast<T>( expr )
This will evaluate to an l-value if T is a reference type -- otherwise it
will evaluate to an r-value.
The same goes for reinterpret_cas t.

I've been trying to write an "implicit_cast" , but I don't think it's
possible to achieve the same behaviour.

For instance, here would be its most basic use:

/* Code Snippet A */

void SomeFunc( signed char ) {}
void SomeFunc( unsigned char ) {}

int main()
{
SomeFunc( implicit_cast<u nsigned char>(45) );
}
But then if we simulatenously try to achieve the l-value behaviour, it
won't compile -- giving an ambiguity error. Here's the code I have so
far:

/* Code Snippet B */
template <class U, class T>
inline U implicit_cast(c onst T& t) { return t; }

template <class U, class T>
inline U implicit_cast(T & t) { return t; }
void SomeFunc(unsign ed char) {}
void SomeFunc(signed char) {}
struct Base {

void SomeConstFuncti on() const {}

};

struct Derived : Base { Derived() {} };
int main()
{
SomeFunc( implicit_cast<u nsigned char>(27) );

SomeFunc( implicit_cast<s igned char>(27) );
Derived derived;

implicit_cast<B ase&>(derived) = Base();
Derived const cderived;

implicit_cast<c onst Base&>(cderived ).SomeConstFunc tion();

/* The line immediately above results in an ambiguity error */
}
(Initially I thought we'd have the problem of "implicit_c ast" creating a
temporary object when its U parameter is a non-reference type, but this
doesn't seem to be a problem because "static_cas t" does the same thing,
e.g.:)

/* Code Snippet C */

#include <iostream>
using std::cout;

#include <cstdlib>

struct Base {

void PrintMyAddress( ) const
{
cout << static_cast<con st void*>(this);

/* Here's an instance where I'd use
implicit_cast */
}

};

struct Derived : Base {};

int main()
{
Derived derived;

static_cast<Bas e>(derived).Pri ntMyAddress();

cout << '\n';

static_cast<Bas e&>(derived).Pr intMyAddress();

cout << '\n';

std::system("PA USE");
}
Any ideas for resolving the ambiguity error in code snippet B?
-Tomás
May 25 '06 #1
8 2017
I've been trying to find a solution for this but haven't come up with
anything. Here's the closest I've gotten:

template <class U, class T>
inline U implicit_cast(c onst T& expr)
{
return static_cast<T&> (expr);
}
The problem though is that if "t" refers to an object which is actually
const, then "T" is STILL a non-const type. If "T" retained its constness,
such that the following defined a local const variable within the function:

T obj;

then the above code snippet would work as desired. But alas, it doesn't.
Of course my first attempt was:

template <class U, class T>
inline U implicit_cast(c onst T& expr)
{
return expr;
}

template <class U, class T>
inline U implicit_cast(T & expr)
{
return expr;
}
but that resulted in ambiguity errors. I'm getting ambiguity errors for the
code snippet immediately above, but why DON'T I get ambiguity errors for
the following:

template<class T>
void Func ( const T& obj ) {}

template<class T>
void Func ( T& obj ) {}

int main()
{
int n = 5;

int const cn = 5;

Func(n);

Func(cn);

Func(5);
}
At first glance, it looks like a compiler bug -- I'm getting ambiguity
errors for "implicit_c ast" simply because it has two template parameters
rather than one, which just doesn't make sense.

-Tomás
May 25 '06 #2
Tomás wrote:
I've been trying to find a solution for this but haven't come up with
anything. Here's the closest I've gotten:

template <class U, class T>
inline U implicit_cast(c onst T& expr)
{
return static_cast<T&> (expr);
}

[...]


Just wanted to ask (without doing much thinking yet)... Is there any
reason you wanted to use the reference argument instead of just 'T'?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 25 '06 #3
* Tomás:
Given the following:

static_cast<T>( expr )
This will evaluate to an l-value if T is a reference type -- otherwise it
will evaluate to an r-value.
The same goes for reinterpret_cas t.

I've been trying to write an "implicit_cast" , but I don't think it's
possible to achieve the same behaviour.

For instance, here would be its most basic use:

/* Code Snippet A */

void SomeFunc( signed char ) {}
void SomeFunc( unsigned char ) {}

int main()
{
SomeFunc( implicit_cast<u nsigned char>(45) );
}
But then if we simulatenously try to achieve the l-value behaviour, it
won't compile -- giving an ambiguity error. Here's the code I have so
far:

/* Code Snippet B */
template <class U, class T>
inline U implicit_cast(c onst T& t) { return t; }

template <class U, class T>
inline U implicit_cast(T & t) { return t; }
void SomeFunc(unsign ed char) {}
void SomeFunc(signed char) {}
struct Base {

void SomeConstFuncti on() const {}

};

struct Derived : Base { Derived() {} };
int main()
{
SomeFunc( implicit_cast<u nsigned char>(27) );

SomeFunc( implicit_cast<s igned char>(27) );
Derived derived;

implicit_cast<B ase&>(derived) = Base();
Derived const cderived;

implicit_cast<c onst Base&>(cderived ).SomeConstFunc tion();

/* The line immediately above results in an ambiguity error */
}
(Initially I thought we'd have the problem of "implicit_c ast" creating a
temporary object when its U parameter is a non-reference type, but this
doesn't seem to be a problem because "static_cas t" does the same thing,
e.g.:)

/* Code Snippet C */

#include <iostream>
using std::cout;

#include <cstdlib>

struct Base {

void PrintMyAddress( ) const
{
cout << static_cast<con st void*>(this);

/* Here's an instance where I'd use
implicit_cast */
}

};

struct Derived : Base {};

int main()
{
Derived derived;

static_cast<Bas e>(derived).Pri ntMyAddress();

cout << '\n';

static_cast<Bas e&>(derived).Pr intMyAddress();

cout << '\n';

std::system("PA USE");
}
Any ideas for resolving the ambiguity error in code snippet B?


First, that given 'Derived derived', the compiler is free to choose T =
'Derived' or 'T = Derived const'. Even if the latter would yield a
compilation error (as long as that error isn't covered by SFINAE rules).
And I think this is what's giving you an ambiguity problem.

So you'd want to enforce the same const'ness for types U and T, e.g.,
instead of specifying the argument type as T, specifying it like
'typename ConstVersion<T, IsConst<U>::yes >::Type&'.

Here's an example of detecting constness, not tested:

template< class T >
struct IsConst
{
static T& aT();
static SizeNFalse isConstArg( T& );
static SizeNTrue isConstArg( T const& );

enum{ yes = sizeof( isConstArg( aT() ) ) == sizeof( SizeNTrue ) };
};
--
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?
May 25 '06 #4
Victor Bazarov posted:

template <class U, class T>
inline U implicit_cast(c onst T& expr)
{
return static_cast<T&> (expr);
}

[...]


Just wanted to ask (without doing much thinking yet)... Is there any
reason you wanted to use the reference argument instead of just 'T'?

Implicit downcast from derived to base, and still retain L-value-ness:
implicit_cast<B ase&>(derived_o bject).SomeMeth od();
-Tomás
May 25 '06 #5
* Alf P. Steinbach:

Here's an example of detecting constness, not tested:

template< class T >
struct IsConst
{
static T& aT();
static SizeNFalse isConstArg( T& );
static SizeNTrue isConstArg( T const& );

enum{ yes = sizeof( isConstArg( aT() ) ) == sizeof( SizeNTrue ) };
};


Uh, those args need to pointers, not references, in case no copy
constructor is available in T. Ditto for result of aT().

--
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?
May 25 '06 #6
Alf P. Steinbach wrote:
* Alf P. Steinbach:

Here's an example of detecting constness, not tested:

template< class T >
struct IsConst
{
static T& aT();
static SizeNFalse isConstArg( T& );
static SizeNTrue isConstArg( T const& );

enum{ yes = sizeof( isConstArg( aT() ) ) == sizeof( SizeNTrue ) };
};


Uh, those args need to pointers, not references, in case no copy
constructor is available in T. Ditto for result of aT().


Why? You're never passing anything by value. You're passing and
returning T's by reference only, so no copy constructor is invoked on a T.
May 25 '06 #7

To put things into perspective, here's a code snippet which uses
"static_cas t". I want to replace all instances of static_cast with
implicit_cast, and to have it behave identically:

void SomeFunc( unsigned char ) {}
void SomeFunc( signed char ) {}

class Base {
public:

Base() {}

void SomeConstFuncti on() const {}

void SomeNonConstFun ction() {}

};

class Derived : public Base
{
public:

Derived() {}

};
int main()
{
/* First we'll work with simple POD literals: */

SomeFunc( static_cast<uns igned char>(76) );
SomeFunc( static_cast<sig ned char>(76) );
/* Now we'll deal with L-value-ness */

Derived derived;

static_cast<Bas e&>(derived) = Base(); /* Just to demonstrate
L-valueness */
static_cast<Bas e&>(derived).So meNonConstFunct ion();
static_cast<con st Base&>(derived) .SomeConstFunct ion();

Derived const c_der;

static_cast<con st Base&>(c_der).S omeConstFunctio n();
// static_cast<Bas e&>(c_der); /* ERROR: Won't compile */

}
I presently have sample code which satisfies all the above requirements,
except that it DOESN'T result in a compile error if you try to compile
the last line of code I wrote above. Here it is:

template<class U, class T>
inline U implicit_cast( const T& expr )
{
return const_cast<T&>( expr);
}
-Tomás
May 25 '06 #8

Here's my latest attempt (but still doesn't compile):
template<class T>
struct Wrapper {

typedef T TypeCV;

TypeCV &stored;

Wrapper( TypeCV &arg ) : stored(arg) {}

operator TypeCV&()
{
return stored;
}

};

template<class U, class T>
inline U implicit_cast( Wrapper<T> expr )
{
typedef typename Wrapper<T>::Typ eCV TypeCV;

return static_cast<Typ eCV&>(expr);
}
/* Here comes the code which has had "static_cas t" replaced
with "implicit_cast" . */
void SomeFunc( unsigned char ) {}
void SomeFunc( signed char ) {}

class Base {
public:

Base() {}

void SomeConstFuncti on() const {}

void SomeNonConstFun ction() {}

};

class Derived : public Base
{
public:

Derived() {}

};
int main()
{
SomeFunc( implicit_cast<u nsigned char>(76) );
SomeFunc( implicit_cast<s igned char>(76) );
Derived derived;
implicit_cast<B ase&>(derived) = Base(); /* Just to demonstrate
L-valueness */

implicit_cast<B ase&>(derived). SomeNonConstFun ction();
implicit_cast<c onst Base&>(derived) .SomeConstFunct ion();

Derived const c_der;

implicit_cast<c onst Base&>(c_der).S omeConstFunctio n();
// implicit_cast<B ase&>(c_der); /* ERROR: Won't compile */

}
-Tomás
May 25 '06 #9

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

Similar topics

25
3360
by: BJörn Lindqvist | last post by:
See: http://www.wxpython.org/quotes.php. especially: "wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first." - Guido van Rossum Guess, that answers my question, but isn't "Tkinter was there first" a very bad answer? :) It is kinda ugly too, so I wonder why it can't be replaced? Or maybe another GUI...
9
2563
by: Oscar Monteiro | last post by:
I´m trying to make an application with if ...something else if ... something else to dinamically change a src script, can't this be done ? and if so why not ? Thanks in advance , Oscar Monteiro <span id="script"> <script type="text/javascript" > script.innerHTML="script src='a.js' "; </script>
83
15629
by: rahul8143 | last post by:
hello, what is difference between sizeof("abcd") and strlen("abcd")? why both functions gives different output when applied to same string "abcd". I tried following example for that. #include <stdio.h> #include <string.h> void main() { char *str1="abcd";
9
4932
by: Miro | last post by:
VB 2003 at the end of the code, this works great. bytCommand = Encoding.ASCII.GetBytes("testing hello send text") udpClient.Send(bytCommand, bytCommand.Length) and this recieves it Dim strReturnData As String = _ System.Text.Encoding.ASCII.GetString(receiveBytes)
8
2461
by: Giovanni R. | last post by:
Take a look at this code (you can execute it): error_reporting(E_ALL); function byVal( $v) {} function byRef(&$v) {} print '<pre>'; byVal ($first); // gives a notice
4
7656
by: MZ | last post by:
Hello! I have got URL address like this: http:\\www.ZZZZ.com?param=10 Is it possible to call and read the GET param parameter value in Javascript? I mean such code in PHP language:
9
3759
by: Cristian | last post by:
algebraic expression 'a*b+c' with CIN .Is it possible? How to transfer the algebraic expression 'a*b+c' to the variable s (all double) with cout in a "Console Application" ? cout<<"Input a,b,c and expression in a,b,c "<<endl; cin>>a; cin>>b; cin>>c;
25
2555
by: Piotr Nowak | last post by:
Hi, Say i have a server process which listens for some changes in database. When a change occurs i want to refresh my page in browser by notyfinig it. I do not want to refresh my page i.e. every 5 seconds, i just want to refresh it ONLY on server change just like desktop applications do. The problem is that refreshing evry n seconds has to much impact on my web server. The refresh action should be taken only when something
10
2177
by: Vin | last post by:
Hi, I just wanted to check if I am missing something or if what I am looking for isn't possible. I have a function with 2 generic parameter types, one of these occurs in the argument list the other doesn't. So the function is like this: void CreateEntities<T, IT>(IList<ITentities){}
0
9655
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...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
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
6749
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
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5535
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.