Re: C++ as a target language
* skaller:
On Tue, 18 Jul 2006 21:52:31 +0000, Larry Evans wrote:
On 07/18/2006 12:54 PM, skaller wrote:
Another problem, the inability
of templates to handle type recursion properly, virtually
rules out any possibility of generating templated code.
Could you define proper type recursion and show why c++'s
method rules out generating templated code?
Sure: there is no way to do this in C++ at the moment:
typedef list[T] = Empty | Cons of T * list[T];
This is Felix notation, similar to that used in ML languages.
In C you'd do this with some hackery like:
struct list { T data; struct list *next; };
If you have a pair template, you want this in C++
template<class T>
typedef list<T> = pair<T, list<T>*>;
There is no way to do this in C++ at all.
I'm not sure what you mean, but sitting down at the keyboard and
implementing a little "functional-language-like" list (instead of just
using std::list ;-) ) based on std::pair, I found the following language
limitations:
* no template typedef (is coming in C++0x, AFAIK)
* verbiage (as I understand it, is also addressed)
More?
<code>
#include <utility> // std::pair
#include <boost/shared_ptr.hpp> // boost::shared_ptr
namespace stdx = boost;
template< typename T >
struct List
{
struct Node;
typedef stdx::shared_ptr<Node> Instance;
struct Node: std::pair< T, Instance >
{
typedef std::pair< T, Instance > Base;
Node() {}
Node( T v, Instance list ): Base( v, list ) {}
};
static Instance null()
{
static Instance theNull;
return theNull;
}
};
template< typename T >
typename List<T>::Instance cons( T const& v, typename List<T>::Instance
list )
{
return List<T>::Instance( new typename List<T>::Node( v, list ) );
}
#include <iostream>
#include <ostream>
int main()
{
typedef List<int> IntList;
for( IntList::Instance list =
cons( 1, cons( 2, cons( 3, IntList::null() ) ) );
list;
list = list->second )
{
std::cout << list->first << std::endl;
}
}
</code>
[snip]
You can of course construct a list:
template<class T>
struct list { T data; list<T> *next; };
The problem is you had to write it out by hand,
you couldn't use the template combinator 'pair',
because type recursion doesn't work.
See above.
But I wonder whether that will be possible with the proposed template
typedef for C++0x?
--
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?
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]