473,748 Members | 11,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

User defined class meta data (type traits?)

Hi,

I'm trying to develop a system where I can register some data/
information about a class. For example

// ClassInfo.h
template <class T>
struct ClassInfo
{
static const std::string tagName;
static const int version;
static const bool isConfigurable;
};

// FooBar.h
class FooBar {...};

// FooBar.cpp
template<const std::string ClassInfo<FooBa r>::tagName = "FooBar";
template<const int ClassInfo<FooBa r>::version = 1;
template<const bool ClassInfo<FooBa r>::isConfigura ble = false;

// main.cpp
....
#include "FooBar.h"
if (ClassInfo<FooB ar>::isConfigur able)
{...}

This does what I originally wanted, which is to allow me to associate
meta-data with some arbitrary class, and have that accessible
throughout the code.

The problem is that since the above relies on static variables being
initialized at runtime, I cannot use any of the data as template
arguments. For example I'd like to be able to do the following :
template<class T, bool isConfigurable>
struct SomeAlgorithmIm p
{
static void Func()
{
//...
};
};

template<class T>
struct SomeAlgorithmIm p<T, true>
{
static void Func()
{
//...
};
};

template<class T>
struct SomeAlgorithm
{
static void Func()
{
SomeAlgorithmIm p<T, ClassInfo<T>::i sConfigurable>: :Func();
}
};

SomeAlgorithm<F ooBar>::Func();
The problem is that ClassInfo<T>::i sConfigurable is not a 'compile
time constant expression'. (it actually can be used as a template
argument but only in the same translation unit as the definition of
the static variable - which limits its usefulness).

Any ideas on how I might be able to achieve this?

At some point I naively thought I can put the following in the header
instead of the translation unit :

template<const bool ClassInfo<FooBa r>::isConfigura ble = false;

which of course works for using it as a template argument, but also
gives you multiple symbols during linking (yet bizarrely VC8 doesn't
seem to mind, g++ does).

I also tried making the ClassInfo class contain a struct which is
redifined per 'T', e.g.

template<class T>
struct ClassInfo
{
struct IsConfigurable;
};

then :
template<>
struct ClassInfo<Foo>: :IsConfigurable
{
enum { Value = 1 };
};

This would have almost worked...had it not been for namespaces.
ClassInfo<T>::I sConfigurable must be defined in the same namespace as
ClassInfo...whi ch in my case is impossible to guarantee.

I could also override the entire contents of ClassInfo. this would let
me to initialize integral types (like the int and bool members above)
within the class body thus avoiding the linker errors. However, this
approach also suffers from the namespace issues (the specialization of
a class must be in the same namespace as the class template itself)
(another thing that VC8 isn't too fussed about either!)

Any other ideas? At the moment I'm leaning towards trying to work
around my design's namespace complications , which would allow me to
use the child struct method above. Either that, or just go with a run
time solution to keep things simple.

Many thanks,

Bill
Oct 29 '08 #1
5 2891
greek_bill wrote:
Hi,

I'm trying to develop a system where I can register some data/
information about a class. For example

// ClassInfo.h
template <class T>
struct ClassInfo
{
static const std::string tagName;
static const int version;
static const bool isConfigurable;
};

// FooBar.h
class FooBar {...};

// FooBar.cpp
template<const std::string ClassInfo<FooBa r>::tagName = "FooBar";
template<const int ClassInfo<FooBa r>::version = 1;
template<const bool ClassInfo<FooBa r>::isConfigura ble = false;

// main.cpp
...
#include "FooBar.h"
if (ClassInfo<FooB ar>::isConfigur able)
{...}

This does what I originally wanted, which is to allow me to associate
meta-data with some arbitrary class, and have that accessible
throughout the code.
[...]

Does the next example demonstrates what you want?

#include <string>
#include <iostream>

struct A1
{
};
struct A2
{
};

template < class T >
struct At
{
};

template<>
struct At< A1 >
{
static std::string Get()
{
return "A1";
}
};
template<>
struct At< A2 >
{
static std::string Get()
{
return "A2";
}
};
int main()
{
std::cout << At< A1 >::Get() << std::endl;
}

Oct 30 '08 #2
>
Does the next example demonstrates what you want?
No, not really. What you're doing is overriding (or rather providing)
Get() in a template specialization and the use that at run time. What
I'd like to do is override/provide something (e.g. an int or a bool)
in a template specialization and use that as a template argument at
compile time.
Oct 30 '08 #3
greek_bill wrote:
Hi,

I'm trying to develop a system where I can register some data/
information about a class. For example

[code]

This does what I originally wanted, which is to allow me to associate
meta-data with some arbitrary class, and have that accessible
throughout the code.

The problem is that since the above relies on static variables being
initialized at runtime, I cannot use any of the data as template
arguments. [...]

Any ideas on how I might be able to achieve this?

At some point I naively thought I can put the following in the header
instead of the translation unit :

template<const bool ClassInfo<FooBa r>::isConfigura ble = false;

which of course works for using it as a template argument, but also
gives you multiple symbols during linking (yet bizarrely VC8 doesn't
seem to mind, g++ does).
You could work around this by implementing this in some 'ClassInfoImp'
which has another template parameter that you don't specialize (and
which doesn't have any semantic meaning). This makes 'ClassInfoImp<F oo>'
a partial specialization, which can/needs to have its members defined
in the header.
Then you derive your 'ClassInfo<Foo> ' from 'ClassInfoImp<F oo,DummyType>'
where 'DummyType' is the one without semantics (and could be 'void*' or
or 'Foo' 'struct DummyType {}' or whatever you prefer).
I also tried making the ClassInfo class contain a struct which is
redifined per 'T', e.g.

template<class T>
struct ClassInfo
{
struct IsConfigurable;
};

then :
template<>
struct ClassInfo<Foo>: :IsConfigurable
{
enum { Value = 1 };
};

This would have almost worked...had it not been for namespaces.
ClassInfo<T>::I sConfigurable must be defined in the same namespace as
ClassInfo...whi ch in my case is impossible to guarantee.
Why is it impossible?
I could also override the entire contents of ClassInfo. this would let
me to initialize integral types (like the int and bool members above)
within the class body thus avoiding the linker errors. [...]
I don't understand this.
Any other ideas? At the moment I'm leaning towards trying to work
around my design's namespace complications , which would allow me to
use the child struct method above. Either that, or just go with a run
time solution to keep things simple.
Compile-time traits are a great tool. :)
Many thanks,

Bill
Schobi
Oct 31 '08 #4
I like the partial base class specialization. ..good idea! :)

but I think it suffers from the same namespace problems. In my setup I
have something like :

namespace Core
{
// ClassInfo template definition here
}

namespace Extension
{
class Foo;

// Ideally I'd like to have the Foo specialization here
template<ClassI nfo<Foo{ ... };
}

The above fails to compile because the specialization of ClassInfo
appears in a different namespace ('Extension') than its definition. To
get this to work, I'd have to have the following :

namespace Extension
{
class Foo;
}

namespace Core
{
template<ClassI nfo<Extension:: Foo{ ... };
}

While this is certainly possible, it forces a code layout restriction
that I'm not comfortable with. Ideally I'd like to keep the
specialization on Foo and Foo's definition as close as possible.

I admit, this isn't a huge problem, but if I could work around it that
I'd rather I did!
btw, I've moved on from this. What I did in the end is to 'discover'
whether a class is 'configurable' by checking for the presence of a
certain function. I find that discovering existing features (traits?)
of a class is generally easier than associating new ones (like I've
been describing above). Most of the relevant material I've read on
this topic (Modern C++, Boost::type_tra its, etc) focus on discovering
features about a class.

Also, as it turns out, in my case it's better to decide whether a
class is configurable based on the presence of a Configure() function.
While I was trying to get the bool 'IsConfigurable ' to work, I found
myself adding a static check (compile time assert) to ensure that if a
class is declared as configurable then it also provides a configure
function.

Anyway, thanks for the good idea though! :)
Compile-time traits are a great tool. :)
Yes, they are!

Bill
Nov 2 '08 #5
greek_bill wrote:
I like the partial base class specialization. ..good idea! :)

but I think it suffers from the same namespace problems. [...]
Yes, it does. Which is the reason I asked why this such
a problem in your case.
[...] To
get this to work, I'd have to have the following :

namespace Extension
{
class Foo;
}

namespace Core
{
template<ClassI nfo<Extension:: Foo{ ... };
}

While this is certainly possible, it forces a code layout restriction
that I'm not comfortable with. Ideally I'd like to keep the
specialization on Foo and Foo's definition as close as possible.

I admit, this isn't a huge problem, but if I could work around it that
I'd rather I did!
If you don't need a fully defined class at the place you
define the traits for that class, you could use a macro that
declares the class and then defines its traits. If the macro
is well documented to be used only in global namespace (and
especially if any other use leads to compile-time errors) it
shouldn't be a problem.
OTOH, when you want to have each class close to its traits,
why don't you define those traits within the class (like STL
iterators and 'std::iterator_ traits' work together)?
btw, I've moved on from this. What I did in the end is to 'discover'
whether a class is 'configurable' by checking for the presence of a
certain function. I find that discovering existing features (traits?)
of a class is generally easier than associating new ones (like I've
been describing above). Most of the relevant material I've read on
this topic (Modern C++, Boost::type_tra its, etc) focus on discovering
features about a class.
Yes, automatically finding out about features, if possible,
is always easier. Especially when later you have to add a
class and mustn't forget about all the traits that come
with it.
[...]
Bill
Schobi
Nov 4 '08 #6

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

Similar topics

9
1370
by: sandSpiderX | last post by:
Hi, I am a C++ SE. I was workingon a project, instantly I thought of trying to declare a class at several blocks, is it possible, like Class X
2
1846
by: maynard | last post by:
Is there a way to check if an object is an instance of a user-defined type or an integral type? I have a templated class that this would be very handy in (do _something_ if the template parameter is integral type, or call a method of the template parameter if it is a user-defined type/class). I know this is quite error prone (e.g., instantiating the template class with a class that doesn't define the required method), but this is just...
0
1860
by: Daimy | last post by:
I meet the same problem below, please help me! Thanks! //written by some one I have developed a windows forms user control, which I am going to host in Internet Explorer.. I am familiar with the security settings requirement inorder to do the
11
5001
by: trinitypete | last post by:
Hi all, I have a user control that uses control literal to build a heading with a link, and a div containing links below. As the link heading is hit, I want to change the style of the div, making it visible or not. Yep you guessed it, expanding tree type functionality. The header has an onclick event onclick='Doexpandcollapse
3
2237
by: Tim::.. | last post by:
Can someone please help.... I'm having major issues with a user control I'm tring to create! I an trying to execute a sub called UploadData() from a user control which I managed to do but for some reason I keep getting the error: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
1
2009
by: Robert | last post by:
I have a large web site converted from 1.1 to 2.0 and in VS 2005, the IDE complains that in the ASPX file (html source): Error 1 Element 'stylesheet' is not a known element. This can occur if there is a compilation error in the Web site. C:\Documents and Settings\...\Local Settings\Temp\1\VWDWebCache\onlineformsdev.....com\sweepv2\dorequest1.aspx 16 7 http://onlineformsdev.....com/ The source code (start of the...
9
2645
by: Bit Byte | last post by:
Can't seem to get my head around the point of a trait class - no matter how many times I read up on it - why not simply use functors or function pointers ? Anyone care to explain this in a simple straightforward way that a simple guy from "Missourah" can understand ?
5
3553
eragon
by: eragon | last post by:
I wrote this function to create a new file when the user posts in my forums, and its not creating a new file, can you help me? this script is not copyrighted as the last one. function createNewFile($name,$mail,$subject,$comments,$count,$date,$other="",$up="0") { global $settings; $header=implode('',file('header.txt')); $footer=implode('',file('footer.txt')); $content=' <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">...
6
2611
by: Dan Smithers | last post by:
I want to write my own class derived from the ostream class. I have been getting errors with my templates: First, I get an error writing a nested template. If I leave the function definition inside template class definition (commented out at //1) then it compiles and runs fine, but if I declare and define the function separately (at //2). Is the following syntax supported by g++?
0
8989
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
8828
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
9537
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...
1
9319
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
8241
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
6795
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
6073
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();...
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
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.