473,785 Members | 2,698 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Template specialization for a group of types

I posted a similar question some time ago, but didn't get an
satisfying answer.

Lets say I have a template and five integer and two floating
types.

template <typename T> class A
{
A() {}
~A() {}

public:
void B( T);
};

// for all int
template <typename T> void B( T)
{
// do something with int (char, unsigned int ...)
}
template<> void B( float)
{
// do something with float
}
template<> void B( double)
{
// do something with double where the code looks the same as for float
}

How to avoid to replicate the code for float and double?
Or is it not possible?

Thanks,
marc

Jul 22 '05 #1
4 2308
Hi Marc,

I just wanted to post the same question :-).

What I do: I use macros for that purpose, but I do not like it :-(. Please
see the code below:

So I would be happy to get a nicer solution as well.

Regards,
Patrick
// ***** CODE *****

struct A_1 {};
struct A_2 {};
struct B_1 {};
struct B_2 {};

// my class bar
template <typename> class bar;

// first GROUP of specializations of bar
#define create_class_A_ bar(CA) \
template <> class bar<CA> \
{ \
typedef CA used_type; \
};

// class definitions Group A
create_class_A_ bar(A_1);
create_class_A_ bar(A_2);

// second GROUP of specializations of bar
#define create_class_B_ bar(CB) \
template <> class bar<CB> \
{ \
typedef CB used_type; \
};

// class definitions Group A
create_class_B_ bar(B_1);
create_class_B_ bar(B_2);

// some usage
int main()
{
bar<A_1>;
bar<A_2>;
bar<B_1>;
bar<B_2>;

return 0;
}
Jul 22 '05 #2
On Thu, 20 Nov 2003 14:25:22 +0900, Marc Schellens
<m_*********@ho tmail.com> wrote:
I posted a similar question some time ago, but didn't get an
satisfying answer.

Lets say I have a template and five integer and two floating
types.

template <typename T> class A
{
A() {}
~A() {}

public:
void B( T);
};

// for all int
template <typename T> void B( T)
{
// do something with int (char, unsigned int ...)
}
template<> void B( float)
{
// do something with float
}
template<> void B( double)
{
// do something with double where the code looks the same as for float
}

How to avoid to replicate the code for float and double?
Or is it not possible?


It is possible:

/* If you can't use boost
template <class T>
struct is_integral
{
static bool const value = false;
};

template<> struct is_integral<int >{static bool const value = true;};
template<> struct is_integral<uns igned>{static bool const value =
true;};
template<> struct is_integral<sho rt>{static bool const value = true;};
template<> struct is_integral<uns igned short>{static bool const value
= true;};
template<> struct is_integral<cha r>{static bool const value = true;};
template<> struct is_integral<uns igned char>{static bool const value =
true;};
template<> struct is_integral<sig ned char>{static bool const value =
true;};
template<> struct is_integral<lon g>{static bool const value = true;};
template<> struct is_integral<uns igned long>{static bool const value =
true;};

//need const/volatile versions, etc. too!
//what about bool?
*/
// The boost version:
#include <boost/type_traits.hpp >
using boost::is_integ ral;

template <typename T> class A
{
public:
A() {}
~A() {}
void B(T);
};

#include <iostream>

template <bool B>
struct B_impl
{
template <class T>
static void impl(T t)
{
std::cout << "Integer version\n";
}
};
template <>
struct B_impl<false>
{
template <class T>
static void impl(T t)
{
std::cout << "Float version\n";
}
};
// for all int
template <typename T> void A<T>::B(T t)
{
B_impl<is_integ ral<T>::value>: :impl(t);
}

int main()
{
A<short> a;
a.B(5);

A<double> b;
b.B(7.5);
}

Tom
Jul 22 '05 #3
Marc Schellens wrote in news:3F******** ******@hotmail. com:
I posted a similar question some time ago, but didn't get an
satisfying answer.

Lets say I have a template and five integer and two floating
types.

template <typename T> class A
{
A() {}
~A() {}

public:
void B( T);
};

// for all int
template <typename T> void B( T)
{
// do something with int (char, unsigned int ...)
}
template<> void B( float)
{
// do something with float
}
template<> void B( double)
{
// do something with double where the code looks the same as for float
}

How to avoid to replicate the code for float and double?
Or is it not possible?

An alternative is a simple refactor:

template < typename T> A< T >::B( T arg )
{
// int version.
}

/* New (?private?) member
template < typename T> A< T >::B_float( T arg )
{
// int version.
}

template <> inline A< float >::B( float arg )
{
B_float( arg );
}

template <> inline A< double >::B( double arg )
{
B_float( arg );
}

If you like typing (or you *need* to generalize),

#include <iostream>
#include <ostream>
#include <limits>

#if 0 /* boost is preferable if you have it */
#include "boost/mpl/if.hpp"
using boost::mpl::if_ c;
#else
template < bool True, typename TrueT, typename FalseT >
struct if_c
{
typedef TrueT type;
};
template < typename TrueT, typename FalseT >
struct if_c< false, TrueT, FalseT >
{
typedef FalseT type;
};
#endif

template < typename T, typename Arg, void (T::*F)( Arg ) >
struct member_ref_1
{
static void apply( T *that, Arg arg )
{
(that->*F)( arg );
}
};
template < typename T > struct A
{
void B_int( T arg ) { std::cerr << "int\n"; }
void B_float( T arg ) { std::cerr << "float\n"; }

void B( T arg )
{
typedef
if_c<
std::numeric_li mits< T >::is_integer ,
member_ref_1< A< T >, T, &A< T >::B_int >,
member_ref_1< A< T >, T, &A< T >::B_float >

::type type
;
type::apply( this, arg );
}
};

int main()
{
A< int > aint;
aint.B( 0 );

A< double > adouble;
adouble.B( 0.0 );
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #4

"Patrick Kowalzick" <Pa************ ***@cern.ch> wrote in message
news:bp******** **@sunnews.cern .ch...
Hi Marc,

I just wanted to post the same question :-).

What I do: I use macros for that purpose, but I do not like it :-(. Please
see the code below:

So I would be happy to get a nicer solution as well.

Regards,
Patrick
// ***** CODE *****

struct A_1 {};
struct A_2 {};
struct B_1 {};
struct B_2 {};

// my class bar
template <typename> class bar;

// first GROUP of specializations of bar
#define create_class_A_ bar(CA) \
template <> class bar<CA> \
{ \
typedef CA used_type; \
};

// class definitions Group A
create_class_A_ bar(A_1);
create_class_A_ bar(A_2);

// second GROUP of specializations of bar
#define create_class_B_ bar(CB) \
template <> class bar<CB> \
{ \
typedef CB used_type; \
};

// class definitions Group A
create_class_B_ bar(B_1);
create_class_B_ bar(B_2);

// some usage
int main()
{
bar<A_1>;
bar<A_2>;
bar<B_1>;
bar<B_2>;

return 0;
}

One possible solution would be the usage of type lists although, as
discussed with Patrick, IMHO would be simply too much overhead for such a
problem. The standard stream library has the same problem to cope with
(overloading of op << for all the different POD types) and there you see
that it's done "by hand". In lack of better ideas I'd personally stick with
the macros. Sure, the statement "macros are evil" is more or less true but
there are exceptions.

Regards
Chris
Jul 22 '05 #5

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

Similar topics

12
4590
by: Surya Kiran | last post by:
Hi all, I've written a function template. say template <class T> fn (T var) { ... } Is there any way, from within the function, can we check what type of argument we've passed on to the function (double, float etc) ?? Thanks in advance,
6
3353
by: Patrick Kowalzick | last post by:
Dear all, I have a question about default template parameters. I want to have a second template parameter which as a default parameter, but depends on the first one (see below). Is something like that possible? Some workaround? Thank you, Patrick
8
7689
by: Agent Mulder | last post by:
Hi group, I have a problem with partial template specialization. In the code below I have a template struct Music with one method, play(), and three kinds of music, Jazz, Funk and Bach. When I specialize Music<Bach>, I expect that the original play() method is available in the specialization, but it is not. How can I fix this? -X
2
5780
by: Jeff | last post by:
/* -------------------------------------------------------------------------- Hello, I was experimenting with class templates and specializing member functions and came across a simple problem which I can't figure out. I have a simple class C with 2 template member objects, and a function print() that prints the value of these objects. I defined a specialization of print() for C<string, char> which is called correctly. Then I wanted...
31
3538
by: nikola | last post by:
Hi all, I was working with a simple function template to find the min of two values. But since I would like the two values to be different (type) I dont know what kind of value (type) it will return. I tried to write something like this: template <class Type1, class Type2, class Type3> Type3 findMin(Type1 x, Type2 y){ return (x < y) ? x : y;
13
2006
by: Imre | last post by:
Please take a look at the following code: template <typename T, typename Enable = void> class A { public: enum { value = 0 }; }; template <typename T>
2
1832
by: Jakob Bieling | last post by:
Hi, I am having trouble with templates. In a non-template class, I have a template function. Now I want to be able to execute different code for all pointer types. But I cannot get the syntax right. Here is small snippet demonstrating the problem. struct bar { template <typename T>
9
3472
by: stephen.diverdi | last post by:
Can anyone lend a hand on getting this particular template specialization working? I've been trying to compile with g++ 4.1 and VS 2005. //------------------------------------------------------------------ // my regular glass class A { }; // my templated class
8
2969
by: flopbucket | last post by:
Hi, I want to provide a specialization of a class for any type T that is a std::map. template<typename T> class Foo { // ... };
6
2619
by: abir | last post by:
i have a template as shown template<typename Sclass Indexer{}; i want to have a specialization for std::vector both const & non const version. template<typename T,typename Aclass Indexer<std::vector<T,A {} matches only with nonconst version. anyway to match it for both? and get if it is const or nonconst? Actually i want 2 specialization, one for std::vector<T,Aconst & non const other for std::deque<T,Aconst & non const.
0
10327
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
10092
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
8973
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
7499
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
6740
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
5381
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
4053
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
2
3647
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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.