473,786 Members | 2,866 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Template pseudo-specialization through compile-time assertions

Greetings.

Some time ago, I had writing a CVector <T, N> class, which implements an
algebraic vector of arbitrary both dimension and scalar type. First, I
defined the interface for the generic algebraic vector class. The
problem I encountered there was that algebraic vectors of some concrete
dimensions were susceptible to include some extra methods not included
in the most generic case. For example, 3-dimensional vectors include the
cross product, an operation not defined over vectors of lesser dimension
(and also greater... but my mathematic knowledge is not so vast); also,
I'd like to include for 2, 3 and 4-dimensional vectors, methods to
access the cartesian coordinates by name (x, y, z and w).

The two alternatives I found (after seeking and asking here for advice)
to deal with this required to write partial specializations of CVector
<T, N> class, a) rewriting all common behaviour or b) inheriting from a
CBaseVector <T, N> class which include that common behaviour.

Recently, I've reviewed CVector <T, N> source code, and I've found
another alternative (which I think is simpler and clearer than the
previous ones). Now, I have only one CVector <T, N> class generic
definition, without partial (or total) specializations , and that class
definition includes all methods expected to be both common or restricted
to certain dimension (N) values. Then, the implementation of those
restricted methods includes compile time assertions to ensure that they
are not used over vectors with wrong dimension values.

I include here a sample of (incomplete, but I hope that enough to
illustrate the explined) source code. First, the class interface:

template <typename T, std::size_t N>
class CVector
{
public:

// Common behaviour
CVector (T const & initval = T());
CVector (CVector <T,N> const & other);

T & operator[] (std::size_t const index);
T const & operator[] (std::size_t const index) const;

CVector <T,N> & operator= (CVector <T,N> const & rhs);

CVector <T,N> & operator+= (CVector <T,N> const & rhs);
CVector <T,N> & operator-= (CVector <T,N> const & rhs);
CVector <T,N> & operator*= (T const & rhs);
CVector <T,N> & operator/= (T const & rhs);

// ...

// Restricted behaviour
CVector (T const & x, T const & y);
// Only for 2-dimensional vectors
CVector (T const & x, T const & y, T const & z);
// Only for 3-dimensional vectors
CVector (T const & x, T const & y, T const & z, T const & w);
// Only for 4-dimensional vectors

void set (T const & x, T const & y);
// Only for 2-dimensional vectors
void set (T const & x, T const & y, T const & z);
// Only for 3-dimensional vectors
void set (T const & x, T const & y, T const & z, T const & w);
// Only for 4-dimensional vectors

T & x ();
// Only for 1- to 4-dimensional vectors
T const & x () const;
// Only for 1- to 4-dimensional vectors

T & y ();
// Only for 2- to 4-dimensional vectors
T const & y () const;
// Only for 2- to 4-dimensional vectors

T & z ();
// Only for 3- to 4-dimensional vectors
T const & z () const;
// Only for 3- to 4-dimensional vectors

T & w ();
// Only for 4-dimensional vectors
T const & w () const;
// Only for 4-dimensional vectors

CVector <T,N> & operator^= (CVector <T,N> const & rhs);
// Cross product, only for 3-dimensional vectors

// ...

private:

// ...
};

And then, a samples of a restricted method implementation:

template <typename T, std::size_t N>
T &
CVector <T,N>::y ()
{
STATIC_ASSERT(( N >= 2) && (N <= 4));

return (*this)[1];
}

STATIC_ASSERT could be any implementation of a compile time assertion
mechanism. For now, I'm using the second variant described in the book
"Modern C++ design: generic programming and design patterns applied", by
Andrei Alexandrescu.

I've successfully tested the described approach. Also, I've found it
clearer than the two previous ones which imply partial specializations ,
and it doesn't duplicate code nor it requires auxiliar classes.

But I still want to ask here about the goodness of this approach. Is it
correct, from a formal point of view? Does it have any weak spot I've
overlooked? Is there any way of further improving the design?

Thank you in advance for your time and your advice.
Jul 23 '05 #1
3 1484


Ruben Campos wrote:
Greetings. [...] And then, a samples of a restricted method implementation:

template <typename T, std::size_t N>
T &
CVector <T,N>::y ()
{
STATIC_ASSERT(( N >= 2) && (N <= 4));

return (*this)[1];
}


Hi Rubén,

I think you can do this in a cleaner way using
boost::enable_i f:

http://boost.org/libs/utility/enable_if.html

Hope this helps,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo

Jul 23 '05 #2
Joaquín M López Muñoz wrote:

Ruben Campos wrote:
Greetings.


[...]
And then, a samples of a restricted method implementation:

template <typename T, std::size_t N>
T &
CVector <T,N>::y ()
{
STATIC_ASSERT(( N >= 2) && (N <= 4));

return (*this)[1];
}

Hi Rubén,

I think you can do this in a cleaner way using
boost::enable_i f:

http://boost.org/libs/utility/enable_if.html

Hope this helps,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo


First of all, thank you for your diligent answer.

I've immediately read the boost::enable_i f documentation, I've test it
(not in depth, for obvious time reasons) and my conclussion is as follows.

The only way boost::enable_i f represents a change from the STATIC_ASSERT
implementation (in the case I described in my first mail) is by moving
the restriction check from method's implementation to method's
declaration. I think this carries two disadvantages: a) first, it makes
the class declaration a bit harder to read; and second, b)
boost::enable_i f must be typed twice, both in function's declaration and
in function's implementation (I'm currently placing each of them into
separate header and source files, also for template classes), and so
must be done with the restriction.

The only advantage I see is that boost::enable_i f provides information
about the restriction directly in the class declaration itself, saving a
user to be addressed to the implementation (which should be kept
hidden). But the same can be made through comments and/or class
documentation (in fact, I've currently included the restriction
description into the comments attached to the function's implementation,
from which Doxygen constructs the class documentation).

So I'm not able to see the way in which boost::enable_i f can help in my
case. Please, correct me if I am wrong, or explain me advantages of
boost::enable_i f that I've not seen.

Thank you for your time.
Jul 23 '05 #3


Ruben Campos ha escrito:
The only way boost::enable_i f represents a change from the STATIC_ASSERT
implementation (in the case I described in my first mail) is by moving
the restriction check from method's implementation to method's
declaration. I think this carries two disadvantages: a) first, it makes
the class declaration a bit harder to read; and second, b)
boost::enable_i f must be typed twice, both in function's declaration and
in function's implementation (I'm currently placing each of them into
separate header and source files, also for template classes), and so
must be done with the restriction.

The only advantage I see is that boost::enable_i f provides information
about the restriction directly in the class declaration itself, saving a
user to be addressed to the implementation (which should be kept
hidden). But the same can be made through comments and/or class
documentation (in fact, I've currently included the restriction
description into the comments attached to the function's implementation,
from which Doxygen constructs the class documentation).

So I'm not able to see the way in which boost::enable_i f can help in my
case. Please, correct me if I am wrong, or explain me advantages of
boost::enable_i f that I've not seen.


Hello again,

Well, I've thought twice and now I realize that boost::enable_i f
is not applicable to your case, as it can only be used with
(member) function templates.

In the case of (member) function templates, the advantage
of boost::enable_i f is that the template, if disabled
for a particuar type T, does not even enter into the
associated overload set: with the static assert technique,
such a template could be selected by the overload resolution
rules only to trigger a compile time fail. But then again,
your case is different as your restricted member functions
are not templates. So, sorry for providing you a misguided
hint.

Best,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo

Jul 23 '05 #4

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

Similar topics

4
4506
by: Stephen Poley | last post by:
The issue of the focus pseudo-class came up a few weeks ago, and I finally got around to trying it out (better late than never ...) The recommended order given for the pseudo-classes is link, visited, focus, hover, active. However: - Mozilla doesn't seem to do anything with the active rule; - IE gets things wrong as usual: it uses the active rule for focus; it ignores the focus rule; - Opera ignores both focus and active rules and...
1
3325
by: Steven T. Hatton | last post by:
ISO/IEC 14882:2003: "5.2.4 Pseudo destructor call The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type named by type-name. The result shall only be used as the operand for the function call operator (), and the result of such a call has type void. The only effect is the evaluation of the postfix- expression before the dot or arrow.
1
1864
by: mast2as | last post by:
Hi there, Here is the conceptual problem i try to find an elegant solution to. I have a template class that I use to save data from a file. The data can be integer, float, double. This is a skeleton code to show precisely what i am talking about. template<class T> class Channel { public:
0
1459
by: Michael Andersson | last post by:
Given a set of classes class A { enum [ ID = 0x0001} }; class B { enum [ ID = 0x0002} }; class B { enum [ ID = 0x0004} }; I wish to generate a composite class, perhaps using something like Alexandrescu's typelists (pseudo-code:)
3
10277
by: Martin Vorbrodt | last post by:
In "C++ Templates, The Complete Guide" i read that template copy-con is never default copy constructor, and template assignment-op is never a copy assignment operator. Could someone please explain how I could declate/override the two. Thanx
2
1321
by: Drew | last post by:
VS.NET 2003 V7.1.3088 - Unmanaged code I'm getting: c:\Proj\pt.h(581) : fatal error C1001: INTERNAL COMPILER ERROR (compiler file 'msc1.cpp', line 2701) Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information Pseudo code:
5
3371
by: Mark Stijnman | last post by:
I am trying to teach myself template metaprogramming and I have been trying to create lists of related types. I am however stuck when I want to make a template that gives me the last type in a list. I started by using a linked list of types with templates like: struct MyClass1 {}; struct MyClass2 {}; struct MyClass3 {}; struct NullType {};
6
2185
by: pcrepieux | last post by:
Hi, I recently meet a problem while "playing" with the state pattern. I was wondering if each of the member function dedicated to handle events open(), close(), ack() could be change to something like process(openEv& ev), process(closeEv& ev), ... no problem with this point. Going further in this way, i thought that the process member function would be a great candidate for a template. Hum ... it is not. The process function have to be...
11
2755
by: mathieu | last post by:
Hi there, I don't think I'll be able to describe my issue correctly, so instead I'll just give a pseudo C++ code I am struggling with. Basically I am looking for a 'pure virtual template' function that I would be able to declare in the base class (*). Thanks for suggestions, -Mathieu
12
2528
by: Peng Yu | last post by:
Hi, Expression template can be used for the implementation of simple operators without using temporaries (e.g. the ones in the book C++ Template). I'm wondering whether expression template is useful for the convolution operation. For example, I have two arrays a1 and a2. To compute the convolution
0
9647
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
10164
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
10110
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
9961
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...
1
7512
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
6745
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
5397
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
4066
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
3
2894
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.