Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Extra libraries, Code snippets, applications etc. » C++ language problems and code snippets » Template problem
Template problem [message #14248] Wed, 20 February 2008 22:54 Go to previous message
bytefield is currently offline  bytefield
Messages: 210
Registered: December 2007
Experienced Member
Hi. I have one example about how to create a "safe" vector inheriting it from STL vector. The code is showed below. I have errors compiling it under Ubuntu.
#include <vector>
#include <iostream>
#include <string>
using namespace std;

struct Entry
{
	string name;
	int number;
};

template< class T > class Vec: public vector< T >
{
public:
	Vec(): vector< T >(){}
	Vec(int s): vector< T >(s){}
	
	T& operator[](int i) { return vector<T>::at(i); }	
	const T& operator[](int i) const { return vector<T>::at(i); } // oups, forgotten to put last const keyword
};

Vec< Entry > tel(1000);

void print_entry(int i)
{
	cout << tel[i].name << ' ' << tel[i].number << '\n';
}

int main()
{
	try
	{
		print_entry(1000);
	}
	catch(out_of_range)
	{
		std::cerr << "Domain error\n";
		return 1;
	}
	catch(...)
	{
		std::cerr << "Unknow exception\n";
		return 1;
	}
	return 0;
}

What could be the problem(s)?

Compiler version:
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --enable-languages=c,c++,fortran,objc,obj-c++,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.1.3 --program-suffix=-4.1 --enable-__cxa_atexit --enable-clocale=gnu --enable-libstdcxx-debug --enable-mpfr --enable-checking=release i486-linux-gnu
Thread model: posix
gcc version 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)



Errors:
vec.cpp: In instantiation of ‘Vec<Entry>’:
vec.cpp:22:   instantiated from here
vec.cpp:19: error: ‘const T& Vec<T>::operator[](int) [with T = Entry]’ cannot be overloaded
vec.cpp:18: error: with ‘T& Vec<T>::operator[](int) [with T = Entry]’
vec.cpp: In function ‘int main()’:
vec.cpp:35: error: expected type-specifier before ‘out_of_range’
vec.cpp:35: error: ‘...’ handler must be the last handler for its try block



L.E: See line 19 const T& operator[](int i) const { return vector<T>::at(i); }
My mistake, now overloading the [] operator work.


cdabbd745f1234c2751ee1f932d1dd75

[Updated on: Thu, 24 April 2008 17:04]

Report message to a moderator

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Try / catch
Next Topic: multiple classes include-problem
Goto Forum:
  


Current Time: Thu Apr 25 05:49:49 CEST 2024

Total time taken to generate the page: 0.02559 seconds