473,763 Members | 8,980 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
cp********@gmai l.com writes:
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?
Yes, this is legal C++. Local is a normal class, but there is a
separate type for each instantiation of wrap<>.
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);
}
Anthony
--
Anthony Williams | Just Software Solutions Ltd
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

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

Oct 24 '08 #11
On Oct 24, 9:45*am, "Fraser Ross" <z...@zzzzzz.co mwrote:
"James Kanze"
Not sure I understand what you are trying to say, but a local
class cannot be used as a template argument.
Its in the draft at 14.3.1/2.
I had heard that there had been a proposal to allow it, but I
was too lazy to look-up whether it had been adopted. But it's
still illegal in current C++ (C++03).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 25 '08 #12
Any non external entity can't be a template argument at present.

I want to use a string literal as an argument for a non-type parameter
but that can't be done. Is that a sensible restriction?

Fraser.
Oct 25 '08 #13
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.
Oct 25 '08 #14
On 2008-10-25 12:08:41 -0400, "Fraser Ross" <z@zzzzzz.comsa id:
>
I want to use a string literal as an argument for a non-type parameter
but that can't be done. Is that a sensible restriction?
Yes. Two string literals with the same sequence of characters can be at
the same address or at different addresses. So:

template <const char *class C
{
};

C<"asdf"c0;
C<"asdf"c1 = c0;

c0 and c1 could be the same type or they could be different types, so
in some cases the initialization of c1 would fail, and in others it
would succeed.

The way to do this is:

const char *param = "asdf";

C<paramc0;
C<paramc1 = c0; // OK

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Oct 25 '08 #15
"Pete Becker"
const char *param = "asdf";

C<paramc0;
C<paramc1 = c0; // OK
param can't be at block scope which loses the locality of symbols. If a
function is small they won't be that far away.

Fraser.
Oct 25 '08 #16
"Pete Becker"
Yes. Two string literals with the same sequence of characters can be
at
the same address or at different addresses. So:

template <const char *class C
{
};

C<"asdf"c0;
C<"asdf"c1 = c0;

c0 and c1 could be the same type or they could be different types, so
in some cases the initialization of c1 would fail, and in others it
would succeed.
That could be the programmers responsibility.

Fraser.
Oct 25 '08 #17
>
the example has small(?) imperfections though:
missing delete ptr and missing return in main,
non-const pure virtual print in Foo etc.
Thank you all for the comments. I hope boost::shared_p tr will solve
the resource issue

template< typename T >
boost::shared_p tr<Foowrap(cons t T& t)
{
class Local : public Foo
{
......
};
return boost::shared_p tr<Foo>(new Local(t));
}

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

Oct 25 '08 #18
cp********@gmai l.com wrote:
I have a local class inside a function template. I am able to wrap
any type in my local class. Is it legal C++?
Yes, and you actually seem to have made decent use of a potentially
confusing language feature. Nicely done.
What type of class is Local?
Local isn't really a class yet. Each non-specialized instantiation of
the "wrap" function template will be a function, and will include, as
part of its definition, a local class called Local. Each such local
class will be distinct from the others. The name Local will be
meaningful only within the context of its enclosing scope, i.e. within
the definition of the function that is an instantiation of the "wrap"
function template. See also section 9.8 of the current standard,
[class.local].
Is it a class template or regular class?
It's part of the primary definition of a function template; IOW, it's a
blueprint for a class definition, but is neither a template nor a class
in its own right.

Local specifically cannot a template, because templates names have
linkage, whereas Local specifically does not. Local isn't even allowed
to have any member templates.

On the other hand, Local is not a class, but part of a code generation
mechanism that is capable of producing classes as needed. Especially
noteworthy is the fact that different instantiations of the function
template will generate entirely distinct classes based on Local; for
example:

struct foo { virtual ~foo() { } };

template<typena me T>
foo* distinct(foo* f =0) {
struct Bar: foo { };
return dynamic_cast<Ba r*>(f) ? 0 : new Bar;
}

struct t1;
struct t2;

#include <iostream>

int main() {
foo* const f = distinct<t1>();
std::cout << !!distinct<t1>( f) << '\n'; // 0
std::cout << !!distinct<t2>( f) << '\n'; // 1
}

class Foo
{
public:
virtual ~Foo() {}
virtual void print() = 0;
};
Foo is a class.
template< typename T >
Foo* wrap(const T& t)
{
As you said, wrap is a function template.
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);
}
Nicely done, except that ownership of the dynamically allocated object
is not clear. You might consider returning a more sophisticated pointer
type, or else making "wrap" a method of a factory object whose
destructor will delete all of the dynamically allocated objects returned
by wrap.

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

Oct 25 '08 #19
On 2008-10-25 14:44:59 -0400, "Fraser Ross" <z@zzzzzz.comsa id:
"Pete Becker"
Yes. Two string literals with the same sequence of characters can be
at
>the same address or at different addresses. So:

template <const char *class C
{
};

C<"asdf"c0;
C<"asdf"c1 = c0;

c0 and c1 could be the same type or they could be different types, so
in some cases the initialization of c1 would fail, and in others it
would succeed.

That could be the programmers responsibility.
Well, okay. But most programmers probably don't want to be responsible
for determining when two identical string literals are merged into one
and when they aren't. It depends on the compiler and on the compiler's
option settings.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Oct 25 '08 #20

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
9387
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
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...
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...
1
7368
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
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.