473,651 Members | 2,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

templated operators for arrays and pointers

suppose I have class that has templated operator[].
I want to have a few overloads/template specializations for different
types. Basicly, the biggest problem I have is to be able to have this:

const char a[] = "this is passed as an array";
const char *p = "this is passed by the address";
x_class x;
x[a] = .. whatever ..;
x[p] = ..;

then x[a] and x[p] call different overloads. For example inside of the
operator[](...) I want to get the length/size of the passed string. In
case if an array is used it's size is known at compile time and with
pointer I need to calculate the length.

I have a solution, but I'm looking for a better example on how to do
this (Note - it should be templated operator[] and not overloads of
functions or operator())
My solution: (a working example of what I mean)
/////////////

#include <iostream>
#include <cstring>
using namespace std;

class x_class{
template<class T>struct size_of{
static inline size_t value(const T &t){
cout << "dynamic version used" << endl;
return strlen(t);
}
};
template<class T, size_t N>struct size_of<T[N]>{
template<class C>static inline size_t value(const C &){
cout << "static version used" << endl;
return sizeof(C) - 1;
}
};

public:
template<class T>void operator[](const T &t)const{
const char *str = &t[0];
size_t len = size_of<T>::val ue(t);
(cout << "passed string => \"").write(str, len) << "\"\n\n";
}
};
int main(int,char*[]){
const char a[] = "this is passed as an array";
const char *p = "this is passed by the address";
x_class x;
x[a]; //length known at compile time
x[p]; //length is calculated at runtime
x["some other string"]; //known at compile time
}

////////
PS I'm also interested to have operator[](int) and operator[](int []
and int *)
and there must be no confusion if I use x[0] (eg const char* or int??)
thanks

Jul 29 '05 #1
4 1509
__PPS__ wrote:
[...]
and there must be no confusion if I use x[0] (eg const char* or int??)


There should be no confusion to a C++ programmer: the type of 0 is 'int'.

I'll think a bit more about your other questions.

V
Jul 29 '05 #2
for me it's clear if I call operator[](0), operaor[](size_t) should be
used, but 0 is also a pointer, so there's ambiguos function call if
both operator[](void* or char*) and op[](size_t) are defined.
there's no problem in this case if I do operator[](size_t)0), or
if there's nontemplated version of opearator[](size_t) overload, and
op[] is templated for pointer type (that was my workaround when I had
op[](size_t) and op[](const char*) at the same time and somewhere in
code I had x[0], which gave error (I think both in gcc and vc71); In
that case I rewrote overload for operator[](const char*) as
template<class T>op[](const T*) and it worked)

check by adding to x_class:
void operator()(size _t i){ cout << "operator()(siz e_t)\n"; }
void operator()(cons t char *i){ cout << "operator()(con st char *)\n";
}
then x[0] is compilation error;
if you change op()(const char*) into:
template<class T>void operator()(cons t T *i){ cout <<
"operator()(con st char *)\n"; }
tjen x[0] calls size_t version without errors

Jul 29 '05 #3
__PPS__ wrote:
for me it's clear if I call operator[](0), operaor[](size_t) should be
used,
Why is it clear? '0' is an "int", not a "size_t". 'int' -> 'size_t'
is a standard integral conversion, which has the same rank as the
conversion from '0' to a pointer (13.3.3.1.1/3).
but 0 is also a pointer,
No, it is NOT. It's a literal of type 'int'.
so there's ambiguos function call if
both operator[](void* or char*) and op[](size_t) are defined.
Yes. Integral conversions and pointer conversions have the same rank.
there's no problem in this case if I do operator[](size_t)0), or
if there's nontemplated version of opearator[](size_t) overload, and
op[] is templated for pointer type (that was my workaround when I had
op[](size_t) and op[](const char*) at the same time and somewhere in
code I had x[0], which gave error (I think both in gcc and vc71); In
that case I rewrote overload for operator[](const char*) as
template<class T>op[](const T*) and it worked)

check by adding to x_class:
void operator()(size _t i){ cout << "operator()(siz e_t)\n"; }
void operator()(cons t char *i){ cout << "operator()(con st char *)\n";
}
then x[0] is compilation error;
if you change op()(const char*) into:
template<class T>void operator()(cons t T *i){ cout <<
"operator()(con st char *)\n"; }
tjen x[0] calls size_t version without errors


Don't use 'size_t'. Use 'int'.

V
Jul 29 '05 #4
the best solution I found uses enable_if, mpl, and type_traits from
boost:

void operator[](const int i)const{
cout << "[int]\n";
}
void operator[](const std::string &s)const{
cout << "[std::string]\n";
}
template<size_t N>void operator[](const char (&t)[N])const{
cout << "[array of " << N << " elements]\n";
}
template<class T>
typename enable_if<
mpl::and_<is_po inter<T>,
is_same<typenam e remove_pointer< T>::type,char>
::type operator[](const T t)const{

cout << "[pointer]\n";
}
now it correctly calls array version, pointer, integer or any other
supplied overload (as with string&)

Aug 2 '05 #5

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

Similar topics

3
6570
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? Here's what I'm generally trying to achieve: I'm building (trying to anyway) a serialization library. Here's my design:
2
2007
by: Thomas Matthews | last post by:
Hi, I would like to create a table (or vector) of pointers to templated functions. 1. How do I declare a typedef of a pointer to a templated function? For example, I have some functions that print out a type's name to an istream:
9
2305
by: Jon Wilson | last post by:
I have a class which needs to accumulate data. The way we get this data is by calling a member function which returns float on a number of different objects of different type (they are all the same type for a given instance of the class, but different types for different instances.) #include<set> using namespace std; template<class T>
27
3116
by: glen herrmannsfeldt | last post by:
The subject recently came up in comp.compilers, though I believe that I asked here before. If you use relational operators, other than == and !=, on pointers to different objects, is there any requirement on the result? #include <stdio.h> int main() {
8
1561
by: Greenhorn | last post by:
Hi, Those relational operators have operands of all numerical type int,char,float etc. They also are working for character arrays. Whats the logic behind their working. Is the length of the array compared first and then each character compared with corresponding character. { const char msg = "msessage}", ch = "Za";
9
2191
by: shaun | last post by:
Dear all, I realized an error in a previous post, I reproduce it here because I'm still not sure how to solve it: I want to make a templated function which points to one-past-the-end of a simple array, to pass to a range constructor for a const vector. Here is some demonstration code: #include <iostream> using namespace std;
28
5071
by: dspfun | last post by:
I'm trying to get a good understanding of how unary operators work and have some questions about the following test snippets. int *p; ~!&*++p--; It doesn't compile, why? The problem seems to be the ++, the compiler says: "Error: invalid l-value in increment". int i = 10; ~!*&i++;
21
2204
by: George Exarchakos | last post by:
Hi everyone, I'd like your help... Can we have a std::list<BASEwhere BASE be the base class of a class hierarchy? I want to add to this list objects that are inherited from BASE class but not necessarily the same... class base { int x;
2
2923
by: domehead100 | last post by:
I have a templated class, CDerived: template <typename TValue, typename TDraw, typename TEdit ...> class CDerived : public CBase { TValue m_Value public: TValue& GetValue() const {
0
8361
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
8278
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8807
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...
1
8466
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
8584
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
5615
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
4290
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2701
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
1
1912
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.