I wanted to provide a template class with an optional data member. The
most natural way to do this was to implement a member for a given
template parameter, and in the case of 'void', then not.
I came up with the following, and I'm wondering if the design is any
good. Perhaps I'm overcomplicatin g things? Or is it ok?
// First we use a helper class that we can specialize on 'void'
template <typename T>
struct DataContainer {
// I'm aware of the problems when T is a reference, but this can
// be easily solved, either with traits, or another
// specialization
typedef T& reference_type;
T contained_;
};
// The empty class for void
template <>
struct DataContainer<v oid> {
typedef void reference_type;
};
// Make use of empty base class optimization to save space in
// the case of 'void'
template <typename vertex_value_ty pe>
class Vertex : private DataContainer<v ertex_value_typ e> {
public:
// A 'void' argument ctor
Vertex() {}
// a templated ctor taking a data argument
// SFINAE+the other overload make this work for T=void
template <typename T>
Vertex(const T& d) {
// we can't use the initializer list here, since
// the base class is dependent, and so contained_
// is not looked up, unless we qualify it. (?)
this->contained_ = d;
}
// when called in the case of 'void' this will error, which
// is good. Otherwise it works fine as the function definition
// will not be checked before use (because template class)
// and the declaration is syntactically fine.
typename DataContainer<v ertex_value_typ e>::reference_t ype
data() {
return this->contained_;
}
~Vertex() {}
};
--
Regards,
Ferdi Smit (M.Sc.)
Email: Fe********@cwi. nl
Room: C0.07 Phone: 4229
INS3 Visualization and 3D Interfaces
CWI Amsterdam, The Netherlands 12 1885
Ferdi Smit wrote: I wanted to provide a template class with an optional data member. The most natural way to do this was to implement a member for a given template parameter, and in the case of 'void', then not.
I came up with the following, and I'm wondering if the design is any good. Perhaps I'm overcomplicatin g things? Or is it ok?
I am wondering what would be the application of it? How would you use it?
I understand the need to store something and get it back, and have the
typedef, and so on, but what would be the meaning of 'Vertex<void>'? What
use do you derive from it?
I realise that having different data contents based on the template
argument is a valid approach (and I've seen if not written some of that),
but what would be the point of *not* having data? Wouldn't you rather
simply undefined 'DataContainer< void>'? I mean, declare it but don't
provide the definition...
// First we use a helper class that we can specialize on 'void' template <typename T> struct DataContainer { // I'm aware of the problems when T is a reference, but this can // be easily solved, either with traits, or another // specialization typedef T& reference_type; T contained_; };
// The empty class for void template <> struct DataContainer<v oid> { typedef void reference_type; };
// Make use of empty base class optimization to save space in // the case of 'void' template <typename vertex_value_ty pe> class Vertex : private DataContainer<v ertex_value_typ e> { public: // A 'void' argument ctor Vertex() {}
// a templated ctor taking a data argument // SFINAE+the other overload make this work for T=void template <typename T> Vertex(const T& d) { // we can't use the initializer list here, since // the base class is dependent, and so contained_ // is not looked up, unless we qualify it. (?) this->contained_ = d; }
// when called in the case of 'void' this will error, which // is good. Otherwise it works fine as the function definition // will not be checked before use (because template class) // and the declaration is syntactically fine. typename DataContainer<v ertex_value_typ e>::reference_t ype data() { return this->contained_; }
~Vertex() {} };
V
Victor Bazarov wrote: Ferdi Smit wrote: I wanted to provide a template class with an optional data member. The most natural way to do this was to implement a member for a given template parameter, and in the case of 'void', then not.
I came up with the following, and I'm wondering if the design is any good. Perhaps I'm overcomplicatin g things? Or is it ok?
I am wondering what would be the application of it? How would you use it? I understand the need to store something and get it back, and have the typedef, and so on, but what would be the meaning of 'Vertex<void>'? What use do you derive from it?
I realise that having different data contents based on the template argument is a valid approach (and I've seen if not written some of that), but what would be the point of *not* having data? Wouldn't you rather simply undefined 'DataContainer< void>'? I mean, declare it but don't provide the definition...
[snip]
I ran into that recently: I implemented a class template for labelled graphs
template < typename VertexLabel, typename EdgeLabel >
class graph {
...
};
Somewhere inside you would have node types like
struct vertex_node {
...
VertexLabel the_label;
...
};
Now, it makes perfect sense to consider graphs that are not labelled or have
only labels for the vertices. In that case, you want to be able to pass a
type that has no values as a template parameter. Thus, I defined, very much
like the OP,
struct empty {};
and the program gracefully deals with stuff like graph<empty,int >.
To the OP: It turns out, that an empty class is even more useful if you make
it compatible with standard container types and streams. Thus I actually
did this:
struct empty {};
std::ostream & operator<< ( std::ostream & ostr, empty const & e ) {
return( ostr << '#' );
}
std::istream & operator>> ( std::istream & istr, empty & e ) {
char chr;
istr >> chr;
if ( chr != '#' ) {
istr.setstate( std::ios_base:: failbit );
}
return( istr );
}
bool operator== ( empty a, empty b ) {
return( true );
}
bool operator!= ( empty a, empty b ) {
return( false );
}
bool operator< ( empty a, empty b ) {
return( false );
}
bool operator<= ( empty a, empty b ) {
return( true );
}
bool operator> ( empty a, empty b ) {
return( false );
}
bool operator>= ( empty a, empty b ) {
return( true );
}
Best
Kai-Uwe Bux
Victor Bazarov wrote: I am wondering what would be the application of it? How would you use it? I understand the need to store something and get it back, and have the typedef, and so on, but what would be the meaning of 'Vertex<void>'? What use do you derive from it?
I've been experimenting with Boost Graph for some weeks now, and it
doesn't quite suit our needs in a natural way (it's too complicated to
make non-trivial extensions). Therefore I decided to implement a simple,
but still somewhat general graph class myself. Now the nodes and edges
may contain data items, but not neccesarily. When using larger graphs
you wouldn't want the overhead of some default data member. I also don't
want to specialize the entire graph class for empty data members; first
of all because it would require 4 seperate combinations, and secondly
it's tedious to maintain seperate implementations while the basics are
the same. I simplified the code here to make it more readable in the
newsgroup. The external property map approach for data caused more
problems than it solved... so internal data is prefered.
I realise that having different data contents based on the template argument is a valid approach (and I've seen if not written some of that), but what would be the point of *not* having data? Wouldn't you rather simply undefined 'DataContainer< void>'? I mean, declare it but don't provide the definition...
That's what I'm wondering about : is there an easier way. I tend to over
complicate C++ code after a day of work... I'm not exactly sure what you
mean here? I do want people to actually use Vertex<void>, it's not just
a safe-guard against someone trying to instantiate the class with void
as a template argument. I do have the nagging feeling I'm having one
redundant level of indirection at the moment. Any thoughts?
--
Regards,
Ferdi Smit (M.Sc.)
Email: Fe********@cwi. nl
Room: C0.07 Phone: 4229
INS3 Visualization and 3D Interfaces
CWI Amsterdam, The Netherlands
Kai-Uwe Bux wrote: I ran into that recently: I implemented a class template for labelled graphs
I love reinventing the wheel ;) This is my case exactly...
Now, it makes perfect sense to consider graphs that are not labelled or have only labels for the vertices. In that case, you want to be able to pass a type that has no values as a template parameter. Thus, I defined, very much like the OP,
struct empty {};
This is useful. One thing tho: are you sure that no extra space is used?
When I tried to have an empty class as data member, it still took up
extra space (gcc4, empty vertex was just as big as a vertex containing
an int). However, even if so, I could use an empty struct and derive
from that. Not directly tho, because you can't derive from ie. int or
float. So basically I'm back to square one then, using a wrapper for the
passed in type, specialized to be empty for void ?
--
Regards,
Ferdi Smit (M.Sc.)
Email: Fe********@cwi. nl
Room: C0.07 Phone: 4229
INS3 Visualization and 3D Interfaces
CWI Amsterdam, The Netherlands
Ferdi Smit wrote: [...] I do want people to actually use Vertex<void>, it's not just a safe-guard against someone trying to instantiate the class with void as a template argument. I do have the nagging feeling I'm having one redundant level of indirection at the moment. Any thoughts?
If so, if Vertex<void> is legal in your system, then I think you're doing
it right. You need DataContainer (I would probably call it DataWrapper)
to derive from. It is going to contribute sizeof(T) when T is not void
and in your design, if used as a base class, DataContainer<v oid> is not
going to contribute to the total size of the derived class. I suppose
your Vertex template does have other members and possibly other base
classes...
As to Kai-Uwe's suggestion about 'empty', you don't have to store it, you
just need to specialise your DataContainer on it.
V
Ferdi Smit wrote: Kai-Uwe Bux wrote: I ran into that recently: I implemented a class template for labelled graphs
I love reinventing the wheel ;) This is my case exactly...
Now, it makes perfect sense to consider graphs that are not labelled or have only labels for the vertices. In that case, you want to be able to pass a type that has no values as a template parameter. Thus, I defined, very much like the OP,
struct empty {};
This is useful. One thing tho: are you sure that no extra space is used? When I tried to have an empty class as data member, it still took up extra space (gcc4, empty vertex was just as big as a vertex containing an int). However, even if so, I could use an empty struct and derive from that. Not directly tho, because you can't derive from ie. int or float. So basically I'm back to square one then, using a wrapper for the passed in type, specialized to be empty for void ?
I did not measure the size. I think there is no requirement for these empty
classes to be optimized away. And I am not even sure if that is allowed
when they are used as data members.
Also, keep in mind that your effort might be entirely in vain anyway: after
all you are going to create vertex and edge nodes dynamically. Chances are
that dynamic allocation of memory for objects restricts the available sizes
to multiples of 16 or even 32 bytes in which case your specialization might
not pay off at all.
Best
Kai-Uwe Bux
Kai-Uwe Bux wrote: [..] I think there is no requirement for these empty classes to be optimized away. And I am not even sure if that is allowed when they are used as data members.
They can only have size 0 if they are base class subobjects. If they are
stand-alone (data members as well), they have size at least 1.
Also, keep in mind that your effort might be entirely in vain anyway: after all you are going to create vertex and edge nodes dynamically. Chances are that dynamic allocation of memory for objects restricts the available sizes to multiples of 16 or even 32 bytes in which case your specialization might not pay off at all.
If they are created in an array, and by tens of thousands at a time, it
might...
V
Ferdi Smit wrote: Kai-Uwe Bux wrote:
[snip] struct empty {};
This is useful. One thing tho: are you sure that no extra space is used? When I tried to have an empty class as data member, it still took up extra space (gcc4, empty vertex was just as big as a vertex containing an int). However, even if so, I could use an empty struct and derive from that. Not directly tho, because you can't derive from ie. int or float. So basically I'm back to square one then, using a wrapper for the passed in type, specialized to be empty for void ?
Ok, so what about something like this:
template < typename T >
struct empty_eliminato r {
T data;
};
struct empty {};
template <>
class empty_eliminato r< empty > {
static empty data;
};
Now you do
template < typename VertexLabel >
struct Vertex : public empty_eliminato r< VertexLabel > {
...
};
And you should be able to use the data field transparently inside
Vertex<empty> and Vertex<int>. The only drawback is that name lookup via
this->data will probably not work. Maybe this idea needs a little bit of
polishing.
Best
Kai-Uwe Bux
Victor Bazarov wrote: Kai-Uwe Bux wrote: [..] I think there is no requirement for these empty classes to be optimized away. And I am not even sure if that is allowed when they are used as data members.
They can only have size 0 if they are base class subobjects. If they are stand-alone (data members as well), they have size at least 1.
Also, keep in mind that your effort might be entirely in vain anyway: after all you are going to create vertex and edge nodes dynamically. Chances are that dynamic allocation of memory for objects restricts the available sizes to multiples of 16 or even 32 bytes in which case your specialization might not pay off at all.
If they are created in an array, and by tens of thousands at a time, it might...
In other words, the only way to enjoy the savings of a zero-sized
object is to first create a non-zero sized object to hold it. I'm
thinking that I could profitably apply a similar technique and offer
every reader of comp.lang.c++ a free car, which I would deliver as soon
as I had received $50,000 to cover the cost of the key. In both cases,
the deal is not a great as it may first seem, and the savings (if any,
in the case of the "free" car) is only incremental and not absolute in
its nature.
Greg This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Gert Van den Eynde |
last post by:
Hi all,
I have a question on interface design: I have a set of objects that are
interlinked in the real world: object of class A needs for example for the
operator() an object of class B. On what arguments do you decide whether to
pass a reference to the object of class B to the member function like this
operator()(classB& objB) or to have in class A a data member (a const
pointer to a class B object or so) and have this set during...
|
by: ma740988 |
last post by:
I'm hoping my post here doesn't fall into the 'hard to say' category,
nonetheless I've been advised that multiple uses of accessor/mutator
(get/set) member functions can be viewed as a 'design flaw'. In that
regard I'm trying to create an 'example' class that's an alternative
to the accessor/mutator approach. To further describe the problem
consider the class BAR (below) which has a member data in_use that FOO
needs visibility into. ...
|
by: madunix |
last post by:
We are a public utility institution established by virtue of the
Securities Law. The Company oversees securities' registration,
deposit, transfer of ownership and clearing and settlement.
The website and the mail server are both hosted in U.S.A. The COMPANY
wishes to improve its website and increase the size of e-mail
pops3/webmail accounts. The COMPANY site is static as it only includes
text pages (SHTM, HTML, PDF, Word Document) and...
|
by: Pete |
last post by:
Before I get started with the question, does anyone have a (single)
good book recommendation for database design? Not an Access-specific
book, but something geared toward helping me figure out *what the user
wants*. I've had brief formal education about data flow diagramming,
but I'm looking for ... more, now that I'm actually running into
problems I think stem from the fact that my users can't explain what
they need done, compounded by...
|
by: Peter M. |
last post by:
Hi all,
I'm currently designing an n-tier application and have some doubts about my
design.
I have created a Data Access layer which connects to the database (SQL
Server) and performs Select, update, delete and inserts. I use dataset
objects to pass data to and from the DAL.
In my GUI (windows forms), I use databinding to bind controls to a datatable
| |
by: Allerdyce.John |
last post by:
I have a design type of quesiton.
What is the advantages of using accessor (a getter/setter method)
instead of making
the attribute 'public'?
If a class has public accessor (a getter/setter method) for its
attribute, why not just make the attribute 'public'? It requires less
code/typing. Or is there something I am missing?
Thank you.
|
by: JoeC |
last post by:
I am a self taught programmer and I have figured out most syntax but
desigining my programs is a challenge. I realize that there are many
ways to design a program but what are some good rules to follow for
creating a program?
I am writing a map game program. I created several objects: board
object that is an array of integers each number 0-5 is a kind of
terrain, a terrain object that is an array of terrain types and each
number of...
|
by: YellowFin Announcements |
last post by:
Introduction
Usability and relevance have been identified as the major factors
preventing mass adoption of
Business Intelligence applications. What we have today are traditional
BI tools that don't work
nearly as well as they should, even for analysts and power users. The
reason they haven't
reached the masses is because most of the tools are so difficult to use
and reveal so little
|
by: Immortal Nephi |
last post by:
I have an idea how to design an object in a better way. I would like
to give you
my thought example. Please let me know what you think if it is best
object design.
Please recommend me any book which it teaches me how to design C++ OOP
better as long
as I know how to program OOP in C++.
Think of ancient 6502 microprocessor which it was used for Commodore,
Atari, and
Apple II. This MPU_6502 is an object of MPU_6502 class. All member
|
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,...
|
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...
| |
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...
|
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,...
|
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();...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |