473,241 Members | 1,486 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

Design issue : "self type" as a default template argument (recursive template arguments)

IR
Hi,

I've been trying to do the following (which doesn't compile) :

template<class T, class F = Example<T
struct Example
{
F foo();
};

which gives me a "recursive type or function dependency context too
complex" error (I don't really understand _why_).

Trying to change the declaration to :

template<class T, class F = Example<T,F
struct Example
{
F foo();
};

just leads me to a "'F' : undeclared identifier" error (which I
fully understand, contrary to the previous error).

The goal I'm trying to achieve is to be able to write both

typedef Example<SomeClassSomeExample;

and

struct OtherExample : public Example<OtherClass,OtherExample>
{
//... whatever
};

SomeExample::foo should have a return type of Example<SomeClass>
(aka. SomeExample due to the typedef), while OtherExample::foo
should have a return type of OtherExample.

I've already done things like these, but without template default
argument, as the base template was then designed to be inherited
from (ctors protected, ...). But in this case, the base template
(Example) can be used "standalone".
The scary part with this one, is that without Example's default
template argument (F), I wouldn't be able to write

typedef Example<SomeClass, Example<SomeClass, ... SomeExample;

due to the recursive nature of the declaration.
So I guess that I must really be doing something wrong.
The only solution I've come up with is something along the lines:

class SelfType {};

template<class T, class F = SelfType>
struct Example
{
private:
template<class Ustruct helper { typedef U Type; };
template<struct helper<SelfType{ typedef Example<TType; };
typedef typename helper<F>::Type FinalType;
public:
FinalType foo();
};

This seems to work as far as I tested it, but I'm not satisfied
mainly due to the "scary part" I mentionned (which leads me to
believe I'm kinda playing with Evil).

Do you think I am missing something?
--
IR
Nov 21 '06 #1
3 2441
* IR:
Hi,

I've been trying to do the following (which doesn't compile) :

template<class T, class F = Example<T
struct Example
{
F foo();
};

which gives me a "recursive type or function dependency context too
complex" error (I don't really understand _why_).
Try do do the compiler's job. The definition of F is (filling in the
default) Example<T, F>, which is Example<T, Example<T, F, which is...
[snip]
typedef Example<SomeClassSomeExample;

and

struct OtherExample : public Example<OtherClass,OtherExample>
{
//... whatever
};

SomeExample::foo should have a return type of Example<SomeClass>
(aka. SomeExample due to the typedef), while OtherExample::foo
should have a return type of OtherExample.
So what's "OtherClass" used for, then?

One solution may be to split the single template definition into a
general one and a specialization.

However, with the vague specification (e.g. "OtherClass") it's difficult
to give an example that wouldn't probably be misleading.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 21 '06 #2
IR
Alf P. Steinbach wrote:
So what's "OtherClass" used for, then?

One solution may be to split the single template definition into a
general one and a specialization.

However, with the vague specification (e.g. "OtherClass") it's
difficult to give an example that wouldn't probably be misleading.
Indeed, I guess I over-simplified the example. My intent was to
extract only the syntactic problem I was running into, but I lost
the global design on the way. So I'll try to be more precise...
I currently have a template class (Example in my previous post)
which acts as a specialized container of objects (T, SomeClass,
OtherClass, ...), using a std::map as its underlying implementation.
For simplicity, I'll pretend that it is a std::map<unsigned,int>, and
get rid of the useless template parameters (policies).

It's member methods almost always return either a reference to itself,
or a modified copy. Most of these methods are symmetrical.
So it could be written:

template< /*original arguments ommitted*/ >
class Base
{
public:
Base();
Base(const Base&);
Base& operator =(const Base&);

Base& foo(int i)
{
// do whatever with i and map_
return *this;
};

Base bar(int i) const
{
Base tmp(*this);
tmp.foo(i);
return tmp;
};
private:
std::map<unsigned,intmap_;
};

FYI foo/bar is actually about 20 pairs of symmetric overriden
functions (FinalType& fn1() / FinalType fn1() const, ...).
Due to the number of template arguments (6), this template class is
_always_ used through a typedef (which in reality often spans over 6-
10 lines, so without typedef the code would be unreadable):

typedef Base< /*...*/ Derived1;
typedef Base< /*...*/ Derived2;
etc...

So Derived1::bar returns a Derived1 (aka. Base</*...*/due to the
typedef), while Derived1::foo returns a Derived1&.
But I now feel the need to add an optional rule enforcer to some of
the derived classes (let's say to Derived2) so I thought I'd do the
following :

template</*...*/>
class Base
{
public:
Base(); // rules_ is initialized to NULL
Base(const Base&);
Base& operator =(const Base&);
~Base();

Base& foo(int i)
{
// do whatever with i and map_
if (rules_)
rules_->Enforce_foo(i,map_);
return *this;
};

Base bar(int i) const
{
Base tmp(*this);
tmp.foo(i);
return tmp;
};
protected:
struct RulesInterface
{
virtual void Enforce_foo(int, std::map<unsigned,int>&) const = 0;
};
Base(const RulesInterface* rules)
// Initialize just like Base(), plus,
rules_(rules)
{
};
private:
std::map<unsigned,intmap_;
const RulesInterface* rules_;
};

so I still can write
typedef Base</*...*/Derived1;

but also

class Derived2 : public Base</*...*/>
{
public:
Derived2() : Base</*...*/>(&myRules_), myRules_() {};
Derived2(const Derived2&);
Derived2& operator =(const Derived2&);
private:
struct MyRules : public Base</*...*/>::RulesInterface
{
virtual void Enforce_foo(int i, std::map<unsigned,int>& m) const
{
// do whatever with i and m
};
};
const MyRules myRules_;
};
A few things about the above code :

1) even though Derived2 passes a pointer to myRules_ while it isn't
yet constructed, it's (more or less) ok since Base doesn't refer to it
in it's ctors nor in it's dtor.

2) any Base derivative is "final" by design (it would make no sense to
derive again from DerivedN).

However the problem with that new version of Base/Derived2 is that the
existing codebase expects Derived2 to return Derived2 objects (or
Derived2& depending on which method is called).
Here I have two choices:

a) either override Base's methods in Derived2 so that they return
Derived2 instead of Base, which means code duplication = The Root Of
All Evil IMO, even worse than what's lying below...

b) or, tweak Base so that it can return a Derived2 object if needed
(which was the reason of my original post).
So now I have my Base template looking like this:

class SelfType{};

template</*... ,*/ class F = SelfType>
class Base
{
template<class U>
struct helper { typedef U Type; };
template<>
struct helper<SelfType{ typedef Base</*...*/Type; };
typedef typename helper<F>::Type FinalType;
public:
Base(); // rules_ is initialized to NULL
Base(const Base&);
Base& operator =(const Base&);
~Base();

FinalType& foo(int i)
{
// do whatever with i and map_
if (rules_)
rules_->Enforce_foo(i,map_);
return static_cast<FinalType&>(*this);
};

FinalType bar(int i) const
{
FinalType tmp(*this);
tmp.foo(i);
return tmp;
};
protected:
struct RulesInterface
{
virtual void Enforce_foo(int, std::map<unsigned,int>&) const = 0;
};
Base(const RulesInterface* rules)
// Initialize just like Base(), plus,
rules_(rules)
{
};
private:
std::map<unsigned,intmap_;
const RulesInterface* rules_;
};
The advantage of this solution is that it doesn't break any old code
(namely, typedef's with F defaulted to SelfType), while still allowing
me to write Derived2 just like I wrote it above, without additional
junk.

The disadvantage is that IMHO this implementation is plain ugly, so we
come to the very reason of my previous post: "do you think there is a
better design?"

I hope the simplified code I just posted isn't too messy, but there
might be a few typos left from the simplification of my original code.

--
IR
Nov 22 '06 #3
IR
Oh well, while double-checking my post for typos, one word I wrote
jumped to my face:

IR wrote:
...(policies).
So I figured out the solution: just add another policy as a template
parameter which default to a "do-nothing" policy...

struct UncheckedPolicy
{
static inline
void Enforce_foo(int i, std::map<unsigned,int>& m) const
{
};
};
struct Derived2Policy
{
static /* inline? depending on the complexity */
void Enforce_foo(int i, std::map<unsigned,int>& m) const
{
// do whatever with i and m
};
};
template< /*... ,*/ class Rules = UncheckedPolicy >
class Base
{
public:
Base();
Base(const Base&);
Base& operator =(const Base&);

Base& foo(int i)
{
// do whatever with i and map_
Rules::Enforce_foo(i,map_);
return *this;
};

Base bar(int i) const
{
Base tmp(*this);
tmp.foo(i);
return tmp;
};
private:
std::map<unsigned,intmap_;
};

typedef Base< /*...*/ Derived1;
typedef Base< /*... ,*/ Derived2Policy Derived2;
This solution has many performance / scalability / type safety /
readability advantages over my previous post, with no (obvious)
drawback.

I was indeed missing something! I can be so blind sometimes...
I'd still be glad to hear about what you think of both designs (my
previous post and this one).

Thanks for your attention anyway. :)

--
IR
Nov 22 '06 #4

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

Similar topics

3
by: Todd Gardner | last post by:
Pardon my extremely ignorant newbie questions. Where can I go to find more information about the "self" argument? Is there something special about the word "self" or did Mr. Guido van Rossum...
1
by: Olaf Meding | last post by:
What does the below PyChecker warning mean? More importantly, is there a way to suppress it? PyChecker warning: ..\src\phaseid\integration.py:21: self is argument in staticmethod My best...
2
by: CoolPint | last post by:
Can anyone kindly explain why non-type template parameters are required by giving some examples where their uses are clearly favourable to other alternatives? I cannot think of any good use for...
20
by: Wayne Sutton | last post by:
OK, I'm a newbie... I'm trying to learn Python & have had fun with it so far. But I'm having trouble following the many code examples with the object "self." Can someone explain this usage in...
2
by: Mark | last post by:
Visual C# .Net Standard 7.1.3088 I'm trying to change the type of application from a windows to a console app. I go into the project properties --> Application --> According to the help, I...
4
by: Ondrej Spanel | last post by:
The code below does not compile with .NET 2003, I get folowing error: w:\c\Pokusy\delegTemplArg\delegTemplArg.cpp(11) : error C2993: 'float' : illegal type for non-type template parameter 'x' ...
2
by: Paul | last post by:
I am moving an existing app written years ago to a new server. It uses Sigma Template 1.3 and Quickform 1.1.1 and PEAR.php,v 1.1.1.1 2004/02/16 The directory structure is like this: /site...
13
by: Kurda Yon | last post by:
Hi, I found one example which defines the addition of two vectors as a method of a class. It looks like that: class Vector: def __add__(self, other): data = for j in range(len(self.data)):...
4
by: danilo.turina | last post by:
Hi all, today I encountered a problem that I'm only able to solve by using reinterpret_cast (and I'd like to avoid it). This was my code until yesterday (omitting includes, "using namespace"...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...

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.