473,657 Members | 2,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

traits class (whats it all about?)

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 ?

Nov 23 '06 #1
9 2634
perhaps due to trait timetable personally set up to feed itself,
nothing that really matters much to the heir !
well, pretty off-topical explanation though but I'd rather think of a
modern model for the shelter at millions of dollars after all rather
than turning myself to be knittie-pickie over what a trait is dealing
with fAnct0rs, :-p

Bit Byte wrote:
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 ?
Nov 23 '06 #2


Deniel Rose' wrote:
perhaps due to trait timetable personally set up to feed itself,
nothing that really matters much to the heir !
well, pretty off-topical explanation though but I'd rather think of a
modern model for the shelter at millions of dollars after all rather
than turning myself to be knittie-pickie over what a trait is dealing
with fAnct0rs, :-p

Bit Byte wrote:
>>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 ?

Huh ?

Nov 23 '06 #3

Bit Byte wrote:
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 ?
Sure you can use functions/functors. But why have to rewrite them if
you can classify templates by the class traits? Instead of specializing
one template specificly for one type, classify reusable templates on
traits.

Consider following the discussion at:
http://www.boost.org/doc/html/boost_typetraits.html

And consult the examples there as well.

Nov 23 '06 #4

Bit Byte wrote:
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 ?
"Think of a trait as a small object whose main purpose
is to carry information used by another object or
algorithm to determine "policy" or "implementa tion details"."
[Bjarne Stroustrup]

a simple example would be copy algorithm
template<class InIt, class OutIt>
OutIt copy(InIt from, InIt to, OutIt dest)
{
while(from != to)
{
*dest = *from;
++from, ++dest;
}
return dest;
}

Now consider a situation like this
char som_str[100];
....
char dest_str[100];
you could use the above function
copy(som_str, som_str+100, dest_str);

but the best way would be to simply
copy memory

so you write another version of copy

template<class InIt, class OutIt>
OutIt copy(InIt from, InIt to, OutIt dest)
{
memcpy(dest, from, to-from);
return dest+(to-from);
}

Now you need some way to tell the compiler
which version to use

so you've come to a situation where if
InIt and OutIt are pointer types and they
point to objects of POD type you want to
use the second version. But if they are
something else you need the first version.

So you write a traits class by combining
the type traits (these are from boost)
template<class InIt, class OutIt>
struct memcopyable
{
// so value will be compile time constant
// which will be true if InIt and OutIt satisfy
// the memcopyable requirement
enum { value =
boost::is_point er<InIt>::value &&
boost::is_pod<b oost::remove_po inter<InIt>::ty pe >::value &&
boost::is_point er<OutIt>::valu e &&
boost::is_pod<b oost::remove_po inter<OutIt>::t ype >::value };
};
Now provide two implementations
One for memcopyable, and one for others

template<bool memcopyable>
struct copy_implementa tion;

template<>
struct copy_implementa tion<false>
{
template<class InIt, class OutIt>
static OutIt copy(InIt from, InIt to, OutIt dest)
{
while(from != to)
{
*dest = *from;
++from, ++dest;
}
return dest;
}
};

template<>
struct copy_implementa tion<true>
{
template<class InIt, class OutIt>
static OutIt copy(InIt from, InIt to, OutIt dest)
{
memcpy(dest, from, to-from);
return dest+(to-from);
}
};

template<class InIt, class OutIt>
OutIt copy (InIt from, InIt to, OutIt dest)
{
return copy_implementa tion<memcopyabl e<InIt,
OutIt>::value>: :copy(from, to, dest);
}

So when you call it as above

char som_str[100];
....
char dest_str[100];
copy(som_str, som_str+100, dest_str);

the compiler will magically select the
memcopy version

Nov 23 '06 #5
Bit Byte wrote:
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 ?
Let's say you need to sum a range of numbers, and you start by:

template <typename Itr>
RETVAL_T sum_up(Itr begin, Itr end)
{
RETVAL_T sum = 0;

for (Itr i = begin; i != end; ++i)
{
sum += *i;
}

return sum;
}

All is good except you don't know what RETVAL_T is. You are only given
the iterator type and that can be anything. You need to know what value
type corresponds to that iterator type.

No problem, use traits. A traits class is what you relate some
compile-time information with a specific type. The
std::iterator_t raits<template relates value type with a specific
iterator type, so we do:

template <typename Itr>
typename std::iterator_t raits<Itr>::val ue_type // RETVAL_T
sum_up(Itr begin, Itr end)
{
typename std::iterator_t raits<Itr>::val ue_type sum = 0;

for (Itr i = begin; i != end; ++i)
{
sum += *i;
}

return sum;
}

Hope this is simple enough for you to grasp!

Regards,
Ben
Nov 24 '06 #6
Bit Byte <ro**@yourbox.c omwrote:
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 ?
Just in case the earlier explanations didn't help...

A traits class is a way to add compile time information to a class
without actually putting it in the class. The reason this is useful is
because with a traits class, one can add compile time information to
intrinsic types (like int, and double,) and types you didn't write and
can't change (like string, list and classes from some vendor.)

It's just that simple.

--
To send me email, put "sheltie" in the subject.
Nov 24 '06 #7

Salt_Peter wrote:
Bit Byte wrote:
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 ?

Sure you can use functions/functors.
Actually, you can't. Many uses of traits, in fact the primary use of
them, simply cannot be provided by functions or functors. Take for
instance code like this:

template < typename Iter_t >
void f(Iter_t)
{
std::iterator_t raits<Iter_t>:: value_type x;
x = *Iter_t;

....
}

How are you going to provide the functionality needed to declare x
using a function or functor?

Since C++ has no meta objects (during runtime) you simply can't provide
that type of functionality in a generic manner using functions or
functors. It's got to be a metafunction or trait blob.

And that should answer the OP's question.

Nov 24 '06 #8

Bit Byte wrote:
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 ?
Below is another example of how traits classes can be used and why you
might want to. Also see:

http://www.boost.org/doc/html/boost_typetraits.html which has an
is_pointer type_trait.
std::char_trait s in <stringand std::numeric_li mits in <limits>
for other examples of commonly used traits classes. Note that recent
designs tend to favour one traits per traits class like the is_pointer
example rather than putting many in one class like char_traits and
numeric_limits.

For more advanced uses and 'metaprogrammin g" see

http://www.boost.org/libs/mpl/doc/index.html

and

http://spirit.sourceforge.net/dl_mor...tml/index.html
//----------

#include <iostream>

// traits class providing info whether T is a pointer
// preferable to use boost or std::tr1 version in practise
template <typename T>
struct is_pointer{
static const bool value = false;
};

template <typename T>
struct is_pointer<T*{
static const bool value = true;
};

//-----------------------

// a functor class specialised (below) on whether T is a pointer
// the default argument is never meant to be used by the user
// and would usually be hidden but exposed here to show the workings.

template <typename T, bool Condition = is_pointer<T>:: value>
struct static_pointer_ info_about;

// the specialisations
template <typename T>
struct static_pointer_ info_about<T, true>{
void operator()()con st
{
std::cout << typeid(T).name( ) << " is a pointer\n";
}
};

template <typename T>
struct static_pointer_ info_about<T, false>{
void operator()()con st
{
std::cout << typeid(T).name( ) << " is not a pointer\n";
}
};

// a function that wraps the low level stuff a bit
template <typename T>
void pointer_info_ab out( T t)
{
static_pointer_ info_about<Tf;
f();
}

// and use ..
int main()
{
const char* hello = "hello"; // hello is a pointer
int n = 1; // int is not

pointer_info_ab out(hello);
pointer_info_ab out(n);

}

regards
Andy Little

Nov 24 '06 #9
On Thu, 23 Nov 2006 15:14:45 +0000, Bit Byte wrote:
>Can't seem to get my head around the point of a trait class - no matter
how many times I read up on it
http://www.cantrip.org/traits.html
Nov 24 '06 #10

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

Similar topics

1
1690
by: Donald 'Paddy' McCarthy | last post by:
Hi, I am having a few problems with a GUI. I am new to traits and wxGlade. I have used wxGlade to create a Form with an embedded space for a CustomWidget. I have the traits demo and would like to edit the traits and have the traits form appear instead of the space left for my CustomWidget. wxGlade produces code with the following hook (last line):
0
3744
by: skscpp | last post by:
What's wrong with the following code? Compiler error is at the bottom. The compiler I am using is gcc version 2.95. ============================= // traits.h ============================= #include <vector> #include <list> #include <set> #include <functional>
5
2390
by: Rex_chaos | last post by:
Hi there, I am learning template programming and there is a problem about traits. Now consider a container and an iterator. Here is the code // tag for const iterator and non-const iterator struct non_const_iterator_tag {}; struct const_iterator_tag {}; // traits template <typename T,
3
1595
by: Raider | last post by:
I'm trying to create a base class who will contain generic algoritms and derived class(es) who will perform problem-specific things. I'm unable to use dynamic polymorphism, because base class know nothing about problem-specific types. I wrote the following code using static polymorphism, but compiler do not allow me to use type traits as a template parameter, the following code not compiles: template <class CT> struct InfoClass {
2
3679
by: Ash | last post by:
Hello everyone ! I am trying to find some sort of a cookbook or more examples for using Enthought Traits to build GUI's. I tried to follow the documentations present at the enthought site, but couldnt get too far - especially on how to handle a control event ? Also while i am on the topic: say i have a list "control" that create using the following two lines:
5
2858
by: Hong Ye | last post by:
Traits is a useful template technique to simplfy the implementation of some classes. however, I met some questions when I tried to understand and implement it. Following is an example of traits template with specializations (copied from Nathan C. Myer's 1995 article): template <class numT> struct float_traits { }; struct float_traits<float{
2
1720
by: Milburn Young | last post by:
I see the STL using class templates accepting a traits and a policy. To me, the traits are the "what" and the policy is the "how". How can a policy know what to do without the traits of the topic? Wouldn't it be better for containers to take a policy template argument and for the policy to take a traits template argument? Consider an allocator (policy) that is going to be used in a multi-threaded environment. The programmer could use...
2
3403
by: Colin J. Williams | last post by:
Using >easy_install -v -f http://code.enthought.com/enstaller/eggs/source enthought.traits The result is: .... many lines ....
5
2883
by: greek_bill | last post by:
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;
0
8326
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
8845
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
8743
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
8522
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
8622
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
7355
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
5647
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
4173
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
2745
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 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.