473,598 Members | 3,252 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

condition on template variables

Hello,

I have a question concerning the template classes and their parameters.
Is it possible to set a condition on the template parameters in a way
that could block the compilation if the condition isn't true?
(e.g. by throwing an error message to the compiler).
And is it possible to use this type of condition to make the compiler
choose the best method (between some others).

Here is an example to illustrate my question:
imagine that my condition is "the variable nb is greater than 1"

template < class T, int nb >
class Foo
{
private:

T _tab[nb];

public:

Foo(T[nb]);

...

}
typedef Foo<float,2> Coord; // this line must compile

typedef Foo<int,3> Example; // this line must compile too

typedef Foo<float,0> Another; // but I want this line to throw an error
to the compiler

// This example illustrate my first question
My second one is about a condition that could choose a method to
compile, during the compilation.

For example, here is what i would expect:

template < class T, int nb >
class Foo2
{
private:

T _tab[nb];

public:

#if( nb==1 )
Foo(T t1);

#else if (nb==2)
Foo(T t1, T t2);

#else if....

...

}

// Of course, this syntax is incorrect because "nb" is unknown by the
"precompile r" before compilation.
I'd like to find some kind of condition on template variables at
compilation time.

If you have an idea, it would be a great help.

Thank you

Yohan Firmy
Feb 22 '06 #1
3 3488
Yohan wrote:
I have a question concerning the template classes and their
parameters. Is it possible to set a condition on the template
parameters in a way that could block the compilation if the condition
isn't true? (e.g. by throwing an error message to the compiler).
Yes, usually. It's called "compile-time assert" (or "assertion" ).
And is it possible to use this type of condition to make the compiler
choose the best method (between some others).
Yes, but that's not the preferred technique.
Here is an example to illustrate my question:
imagine that my condition is "the variable nb is greater than 1"

template < class T, int nb >
class Foo
{
private:

T _tab[nb];

public:

Foo(T[nb]);
This declaration looks fishy.

...

}
typedef Foo<float,2> Coord; // this line must compile

typedef Foo<int,3> Example; // this line must compile too

typedef Foo<float,0> Another; // but I want this line to throw an
error to the compiler
It will because zero-sized arrays are not allowed. But not until you
actually try using 'Another'. A simple "typedef" does not cause the
template to be instantiated. Only an attempt to instantiate your
template will cause the compiler to try to allocate the array of size
'nb'.
// This example illustrate my first question
My second one is about a condition that could choose a method to
compile, during the compilation.

For example, here is what i would expect:

template < class T, int nb >
class Foo2
{
private:

T _tab[nb];

public:

#if( nb==1 )
Foo(T t1);

#else if (nb==2)
Foo(T t1, T t2);

#else if....

...

}

// Of course, this syntax is incorrect because "nb" is unknown by the
"precompile r" before compilation.
Template _specialisation s_ are in the language exactly for that.
I'd like to find some kind of condition on template variables at
compilation time.

If you have an idea, it would be a great help.


Yes, plently of opportunities exist. Perhaps you should simply devote
some time to _learning_ templates and what they offer instead of making
guesses and asking for hints or ideas. I strongly recommend the book
"C++ Templates" by Vandevoorde and Josuttis.

V
--
Please remove capital As from my address when replying by mail
Feb 22 '06 #2
Yohan wrote:
Hello,

I have a question concerning the template classes and their parameters.
Is it possible to set a condition on the template parameters in a way
that could block the compilation if the condition isn't true?


Boost uses this technique a lot:

http://www.boost.org/doc/html/boost_staticassert.html
http://www.boost.org/doc/html/boost_.../category.html

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Feb 22 '06 #3
Yohan <yo*****@gmail. com> wrote:
I have a question concerning the template classes and their parameters.
Is it possible to set a condition on the template parameters in a way
that could block the compilation if the condition isn't true?
(e.g. by throwing an error message to the compiler).
And is it possible to use this type of condition to make the compiler
choose the best method (between some others).


Here is a proposal from Dr. Stroustrup about introducing a type system
for templates (called "concepts") that may be of interest.

http://www.research.att.com/~bs/popl06.pdf

--
Marcus Kwok
Feb 22 '06 #4

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

Similar topics

2
5981
by: Chris | last post by:
I have tableA, defined as: field1 varchar2(10), field2 varchar2(10), field3 varchar2(10) I have host variables defined as: v1 pic x(10) varying v2 pic x(10) varying
9
8313
by: Andrea Maschio | last post by:
Hi, i have a terrible noobie frustration formatting an XML file like this: <Dipendente Id="1" Anno="2003" Nome="pippo" Cognome="pippi" Nato_il="10/03" Email="pippo@emailprovider.it" Esito="ok"/> On the XSLt file relayed to this XML, i wrote in green the attribute value if Attribute "Esito" is "Ok". I mean, something, like this:
10
5493
by: noleander | last post by:
I've got an application that uses Pthread to do threading. Mostly Im using Condition Variables and the associated function calls: - pthread_cond_wait() - pthread_cond_signal() - pthread_cond_broadcast() My boss says we cant use Pthread because of licensing issues (LGPL) .. we can only use Native Win32 threading/mutex functions.
5
7971
by: steven | last post by:
Hello, I've created a Word-template for a letter. I've made some fields in the template (such as 'customer number', 'name', ...) as follows: insert field - DocVariabele with name 'customer number' and 'name'. Now I want to fill these fields from my application and print them: Dim myWord As New Word.Application myWord.Documents.Add("c:\template.dot")
9
2219
by: jc | last post by:
Hi all, I have a data type to use that I can't modify its codes. E.g. This template data type is data_type. When I declare a variable of this data_type, I write as following: data_type(8, 2) x; // Declare a data_type variable Someone can confirm me that arguments in template data types must be
5
3596
by: mast2as | last post by:
Hi guys Here's the class I try to compile (see below). By itself when I have a test.cc file for example that creates an object which is an instance of the class SpectralProfile, it compiles fine. 1 / Now If I move the getSpectrumAtDistance( const T &dist ) method definition in SpectralProfofile.cc let's say the compiler says core/profile.cc:199: error: `kNumBins' was not declared in this scope
2
3447
by: Tony | last post by:
What's all the hullabuloo dissing events in favor of condition variables? Is it just certain uses of events (Win32 events that is) that is seen as bad practice? And can't they be used just like condition variables anyway? Anyone have a link to a discussion of such? And is this question OK in here or better in a general programming group? Tony
0
1284
by: Orin | last post by:
Hi, Here is my task: - need to get text from a template variable. For example we have a text with templates "Cars" and "Producers": "{{Cars|Toyota=blablabla |Moskvitch=blablabla |BMW=blabla ...}} {{Producers|TableLTD=blablabla |PhoneINC=Developed in 1998 in Kiev,
9
4026
by: rtalbot | last post by:
I've got a container that looks like this: template <class T> class Foo { public: Foo() : _data(), _status(1) { } Foo(T) : _data(T), _status(0) { } ~Foo() { }
0
7987
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
8392
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
8397
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
8050
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
8264
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
6718
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
5438
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
3939
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1504
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.