473,763 Members | 8,483 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Crazy Local Class

Hi,
I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?
Thanks in advance.
--dhina
---------------------------------------------------------------------------------------------------------------------------------------------
class Foo
{
public:
virtual ~Foo() {}
virtual void print() = 0;
};

template< typename T >
Foo* wrap(const T& t)
{
class Local : public Foo
{
public:
Local(const T& t):val_(t) { }
void print()
{
cout << "In Local::print()" << val_ << endl;
}
private:
T val_;
};
return new Local(t);
}

int main(void)
{
int x = 50;
Foo* ptr = wrap(x);
ptr->print();
std::string s("wrap");
ptr = wrap(s);
ptr->print();
}

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Oct 23 '08
28 2567
On 23 ĎËÔ, 06:58, cplusle...@gmai l.com wrote:
Hi,
š š šI have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? šIs it a class template or regular class?
š š šThanks in advance.
Using local classes as template parameters is prohibited in current C+
+ standard. There's a proposal for C++0x - N2657.

Passing local classes as template parameters known to work in MSVC.
However, doing such thing in an inline function may cause link error.

Local is regular class, there's no such thing as local template.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Oct 25 '08 #21

<cp********@gma il.comwrote in message
news:e7******** *************** ***********@t54 g2000hsg.google groups.com...
Hi,
I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?
Thanks in advance.
--dhina
---------------------------------------------------------------------------------------------------------------------------------------------
class Foo
{
public:
virtual ~Foo() {}
virtual void print() = 0;
};

template< typename T >
Foo* wrap(const T& t)
{
class Local : public Foo
{
public:
Local(const T& t):val_(t) { }
void print()
{
cout << "In Local::print()" << val_ << endl;
}
private:
T val_;
};
return new Local(t);
}

int main(void)
{
int x = 50;
Foo* ptr = wrap(x);
ptr->print();
^^^^^^^^^^^^^^^ ^^^^

delete ptr;

std::string s("wrap");
ptr = wrap(s);
ptr->print();
^^^^^^^^^^^^^^^ ^^^^

delete ptr;

}

You have memory leaks. BTW, excuse me for being so dense, but what
advantages does this technique have over something like:
_______________ _______________ _______________ _______________ ________
#include <iostream>
#include <string>
struct foo_impl {
virtual ~foo_impl() = 0;
virtual void print() const = 0;
};
foo_impl::~foo_ impl() {
std::cout << "In (" << this <<
")->foo_impl::~foo _impl()" << std::endl;
}
typedef foo_impl const& foo;
template<typena me T>
class wrapper : public foo_impl {
T m_obj;

void print() const {
std::cout << "In (" << this <<
")->wrapper<T>::pr int - " << m_obj << std::endl;
}

public:
wrapper(T const& obj)
: m_obj(obj) {
}

~wrapper() {
std::cout << "In (" << this <<
")->wrapper<T>::~w rapper() - " << m_obj << std::endl;
}
};
template<typena me T>
static wrapper<T>
wrap(T const& obj) {
return wrapper<T>(obj) ;
}
int main(void) {
int x = 5;
foo fx = wrap(x);
fx.print();
std::string s("wrap");
foo fs = wrap(s);
fs.print();
return 0;
}
_______________ _______________ _______________ _______________ ________


Thanks.

Oct 26 '08 #22

"Chris M. Thomasson" <no@spam.invali dwrote in message
news:P%******** **********@news fe07.iad...
>
<cp********@gma il.comwrote in message
news:e7******** *************** ***********@t54 g2000hsg.google groups.com...
>Hi,
I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?
Thanks in advance.
--dhina
---------------------------------------------------------------------------------------------------------------------------------------------
[...]
>}


You have memory leaks. BTW, excuse me for being so dense, but what
advantages does this technique have over something like:
_______________ _______________ _______________ _______________ ________
[...]
_______________ _______________ _______________ _______________ ________
Are you going for delegates? If so, well, one can easily modify ScopeGuard:

http://www.ddj.com/cpp/184403758

to return dynamically created objects than can be effectively used as fairly
efficient delegates/futures.

Oct 26 '08 #23

<cp********@gma il.comwrote in message
news:e7******** *************** ***********@t54 g2000hsg.google groups.com...
Hi,
I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?
Thanks in advance.
--dhina
---------------------------------------------------------------------------------------------------------------------------------------------
class Foo
{
public:
virtual ~Foo() {}
virtual void print() = 0;
};

template< typename T >
Foo* wrap(const T& t)
{
class Local : public Foo
{
public:
Local(const T& t):val_(t) { }
void print()
{
cout << "In Local::print()" << val_ << endl;
}
private:
T val_;
};
return new Local(t);
}

int main(void)
{
int x = 50;
Foo* ptr = wrap(x);
ptr->print();
^^^^^^^^^^^^^^^ ^^^^

delete ptr;

std::string s("wrap");
ptr = wrap(s);
ptr->print();
^^^^^^^^^^^^^^^ ^^^^

delete ptr;

}

You have memory leaks. BTW, excuse me for being so dense, but what
advantages does this technique have over something like:
_______________ _______________ _______________ _______________ ________
#include <iostream>
#include <string>
struct foo_impl {
virtual ~foo_impl() = 0;
virtual void print() const = 0;
};
foo_impl::~foo_ impl() {
std::cout << "In (" << this <<
")->foo_impl::~foo _impl()" << std::endl;
}
typedef foo_impl const& foo;
template<typena me T>
class wrapper : public foo_impl {
T m_obj;

void print() const {
std::cout << "In (" << this <<
")->wrapper<T>::pr int - " << m_obj << std::endl;
}

public:
wrapper(T const& obj)
: m_obj(obj) {
}

~wrapper() {
std::cout << "In (" << this <<
")->wrapper<T>::~w rapper() - " << m_obj << std::endl;
}
};
template<typena me T>
static wrapper<T>
wrap(T const& obj) {
return wrapper<T>(obj) ;
}
int main(void) {
int x = 5;
foo fx = wrap(x);
fx.print();
std::string s("wrap");
foo fs = wrap(s);
fs.print();
return 0;
}
_______________ _______________ _______________ _______________ ________


Thanks.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Oct 26 '08 #24

"Chris M. Thomasson" <no@spam.invali dwrote in message
news:P%******** **********@news fe07.iad...
>
<cp********@gma il.comwrote in message
news:e7******** *************** ***********@t54 g2000hsg.google groups.com...
>Hi,
I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?
Thanks in advance.
--dhina
---------------------------------------------------------------------------------------------------------------------------------------------
[...]
>}


You have memory leaks. BTW, excuse me for being so dense, but what
advantages does this technique have over something like:
_______________ _______________ _______________ _______________ ________
[...]
_______________ _______________ _______________ _______________ ________
Are you going for delegates? If so, well, one can easily modify ScopeGuard:

http://www.ddj.com/cpp/184403758

to return dynamically created objects than can be effectively used as fairly
efficient delegates/futures.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Oct 26 '08 #25
Chris M. Thomasson wrote:
<cp********@gma il.comwrote
> I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?
<snipCode to define an abstract interface, and a function template
whose instantiations return pointers to dynamically allocated instances
of local classes implementing the interface. (Whew.) </snip>
You have memory leaks. BTW, excuse me for being so dense,
You're excused. ;)
but what
advantages does this technique have over something like:
struct foo_impl {
virtual ~foo_impl() = 0;
virtual void print() const = 0;
};
Boo. A class called foo_impl with only pure virtual methods is a
contradiction in terms.
typedef foo_impl const& foo;
Boo. A reference type whose name does not end in "ref" or "reference"
is a debugging mess waiting to happen. Just wait until some unwary
client tries to create a vector<foo>.

<snipCode that replaces the OP's local classes with instantiations of
a template that all derive from the common interfaces, and avoids the
OP's dynamic allocation by returning the instances by value (and
requiring the client code to bind those temporary instances to
const-references). </snip>

Boo to your deprecated use of static. And in what way is std::endl
superior to '\n'? If there's really a need to flush std::cout's buffer,
and if the code might run on a platform where '\n' doesn't cause that to
happen anyway, wouldn't it be clearer to call flush directly?
Furthermore, boo to main(void), which is in no way clearer than main().

Bravo to your replacement of dynamic allocation with automatic. Still,
your code does not achieve the same thing as the OP's:

(1) Your client can't call non-const methods of foo, whereas the OP's
client can. You've changed the interface's only method to be const, but
that changes the meaning, and breaks any subclasses not included in the
posted code.

(2) You can't treat pretend a reference is an object for anything other
than trivial use. You can't have collections of them, for example.

(3) You can't pass your wrappers any farther up the stack (in contrast
to the OP's pointers to free store). For example:

foo rewrap(int i) { return wrap(i); }

int main() {

// ok
foo f = wrap(5); f.print();

// run-time error: pure virtual method called
foo g = rewrap(5); g.print();

return 0;
}

(4) I foresee type-slicing problems. I'm not sure where they're hiding
yet, but I can smell them from here.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Oct 27 '08 #26
On 25 Okt., 17:28, "Fraser Ross" <z...@zzzzzz.co mwrote:
In the standards example below neither constructor is accessible and
only one is used.

template<class T, char* pclass X {
X();
X(const char* q) { *}};

X<int, "Studebaker "x1; // error: string literal as template-argument
char p[] = "Vivisectionist ";
X<int,px2; // OK

Fraser.
You need external linkage:

char const* Studebaker = "Studebaker ";
X<int, "Studebaker "x1; // no error

I took the liberty to assume you intended to use a char const* as the
nontype parameter. If not your code looks rather suspicious.

/Peter
Oct 27 '08 #27
"peter koch"
>You need external linkage:
I was asking why its necessary. Pete gave a reason.

Fraser.
Oct 28 '08 #28

"Jeff Schwab" <je**@schwabcen ter.comwrote in message
news:_b******** *************** *******@giganew s.com...
Chris M. Thomasson wrote:
><cp********@gm ail.comwrote
>> I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++? What type of class is
Local? Is it a class template or regular class?

<snipCode to define an abstract interface, and a function template
whose instantiations return pointers to dynamically allocated instances
of local classes implementing the interface. (Whew.) </snip>
>You have memory leaks. BTW, excuse me for being so dense,
[...]

Bravo for your comments; thank you. I am a C programmer, not C++. Oh SHI%!

[BTW, this got rejected on comp.lang.c++.m oderated!!!]
Oct 31 '08 #29

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

Similar topics

12
2685
by: Gnolen | last post by:
Hi, I am really getting crazy here! I just do not get why this happens with the borders of the td/tr! I just want a border on the bottom of the rows(or td) but I just can't do it!!! I have tried so many different ways but I just thought this would do it: td {border-bottom: #000000 1px solid;} But no! What am I doing wrong? Because I can have a border of a td or tr in FF, right?! Thankful for any help here! Table and CSS is below..
3
383
by: INGSOC | last post by:
I spent a few hours today setting up remote debugging in VS.2003 I had to disable the firewall, subvert the security scheme and let anonymous users have full access to my COM+ objects on my Windows XP workstation, but other than that, it was smooth sailing. And, oh yeah. I also have to run remote desktop sharing terminal between my XP workstation and the W2K target or I can't RPC to the destination machine.
19
1712
by: Daniel Billingsley | last post by:
I think it's really nice to be able to do code like someVariable = someMethod(new SomeClass("some text")); However, as method signatures are number and types of parameters, you're limited to having one constructor that accepts a single string, for example. Call me crazy, but wouldn't it be useful to be able to have a syntax where you could set properties in a statement like the one above, without being limited to just what you could...
2
1020
by: rooster575 | last post by:
Im getting the following error on a page where I try to access an external web service. Every time I get the error the .dll name is different! Thanks for any help. ============================================================================ = System.Web.HttpUnhandledException: Exception of type System.Web.HttpUnhandledException was thrown. --->
11
3033
by: GaryB | last post by:
Hi Guys, I've been battling with this one for hours - I hope that you can help me! My code modifies the <aon a page, from a standard document link into a link with a tailored onclick event. It works perfectly (assigning the correct images and the correct onclick events to the correct <atags):
2
3629
by: kheitmann | last post by:
OK, so I have a blog. I downloaded the "theme" from somewhere and have edited a few areas to suit my needs. There are different font themes within the page theme. Long story short, my "Text Posts" are supposed to be in the font: Georgia, but they are showing up in "Times New Roman"...blah! I can't find anything wrong in the code, but who am I trying to fool? I know nothing about this stuff. The code is below. The parts that I *think*...
0
9564
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
10002
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...
1
9938
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
9823
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...
0
8822
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...
0
6643
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
5270
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...
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
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.