473,725 Members | 1,740 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 2010
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
3350
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
2559
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
15588
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
4923
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
2458
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
7654
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
3755
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
2545
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
2169
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
8872
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
9392
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
9246
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
8069
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
6694
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
4505
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...
1
3211
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2619
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2150
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.