473,804 Members | 3,478 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const parameters to template class member functions

I have run into a peculiar problem, in which the following sample code
does not compile (gcc 3.3). I have a template class with a member
function that should take a const version of the template parameter.
However, when I try to use the class with (T=int*), the compiler seems
to ignore the const and gives an error if I pass a const int*. Any
help would be much appreciated.

Kenneth

// test.cpp: In function `int main()':
// test.cpp: error: invalid conversion from `const int*' to
`int*'
// test.cpp: error: initializing argument 1 of `int
myclass<T>::che ck(T)

#include <stdio.h>

template<class T>
class myclass {
T x;
public:
myclass(T x0):x(x0) {}

int check(const T y) { return x==y; }

// compiles fine with this line: T is explicitly replaced by int*
// int check(const int* y) { return x==y; }
};

int main() {
int k;
myclass<int*> mc(&k); // T = int*

const int* p = &k;

printf("%d\n",m c.check(p)); // calling check() causes the error

return 0;
}

Jul 22 '05 #1
5 1782
Kenneth Massey wrote:
I have run into a peculiar problem, in which the following sample code
does not compile (gcc 3.3). I have a template class with a member
function that should take a const version of the template parameter.
However, when I try to use the class with (T=int*), the compiler seems
to ignore the const and gives an error if I pass a const int*. Any
help would be much appreciated.
int check(const T y) { return x==y; }
For T = int*, y is a constant pointer to a non-constant int.

// compiles fine with this line: T is explicitly replaced by int*
// int check(const int* y) { return x==y; }


In this case, y is a non-constant pointer to constant int.

Jul 22 '05 #2
Makes sense.

Is there any way to get the latter behavior, definint the function with the
template parameter instead of hard coding int* ?

Thanks
int check(const T y) { return x==y; }


For T = int*, y is a constant pointer to a non-constant int.

// compiles fine with this line: T is explicitly replaced by int*
// int check(const int* y) { return x==y; }


In this case, y is a non-constant pointer to constant int.


Jul 22 '05 #3
Kenneth Massey posted:
Makes sense.

Is there any way to get the latter behavior, definint the function with the template parameter instead of hard coding int* ?

#include <stdio.h>

template<class T>
class myclass {
T x;
public:
myclass(T x0):x(x0) {}

int check(T y) { return x==y; }

// compiles fine with this line: T is explicitly replaced
by int*
// int check(const int* y) { return x==y; }
};

int main() {
int k;
myclass<const int*> mc(&k); // T = int*

const int* p = &k;

printf("%d\n",m c.check(p)); // calling check() causes
the error

return 0;
}
-JKop
Jul 22 '05 #4
Kenneth Massey wrote:
...


Please don't top-post. I rearranged it.
int check(const T y) { return x==y; }


For T = int*, y is a constant pointer to a non-constant int.

// compiles fine with this line: T is explicitly replaced by int*
// int check(const int* y) { return x==y; }


In this case, y is a non-constant pointer to constant int.


Makes sense.

Is there any way to get the latter behavior, definint the function with the
template parameter instead of hard coding int* ?


If you don't mind hard-coding T*, then

int check(T const *y) ...

and substitute 'T' with 'int' (the pointer bit is already accounted for).

Otherwise, consider a simple fact that 'const' and types should be always
placed in a particular order to understand how type substitution works:

int check(T const y) // const goes _after_ the type

Now, even if you replace 'T' with 'int*', you get

int check(int* const y) // easier to understand, isn't it?

.. To get the same thing as

int check(int const *y)

you need to make your 'T' 'int const*'.

Also remember that top-level consts do not really count (or do anything
useful):

int check(int* const y)

is really quite equivalent to

int check(int* y)

V
Jul 22 '05 #5

"Kenneth Massey" <ke******@vt.ed u> wrote in message
news:mjRKc.3073 $_K2.192@lakere ad02...
Makes sense.

Is there any way to get the latter behavior, definint the function with the template parameter instead of hard coding int* ?


Something like this (untested) which uses partial template specialisation to
transform T* into const T*.

template <class T>
struct MakeConstPointe r
{
typedef T type;
};

template <class T>
struct MakeConstPointe r<T*>
{
typedef const T* type;
};

template <class T>
struct MakeConstPointe r<const T*>
{
typedef const T* type;
};

template<class T>
class myclass {
T x;
public:
myclass(T x0):x(x0) {}

int check(typename MakeConstPointe r<T>::type y) { return x==y; }
};

Of course your compiler must support partial template specialisation, which
all modern compilers do.

john
Jul 22 '05 #6

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

Similar topics

6
3490
by: Thomas Matthews | last post by:
Hi, How do I create a const table of pointers to member functions? I'm implementing a Factory pattern (or jump table). I want to iterate through the table, calling each member function until a non-zero index is returned. Below is my attempt, which generates compiler errors: namespace Reference {
4
1810
by: NKOBAYE027 | last post by:
Hi Everyone: Short description first MathematicalSet is to be a class template that's supposed to behave as the name suggests. It has functions that define union, contains, is_contained_in, etc... I want the thing to behave like a normal collection as well. That is to comply with the ansi standard for STL collections even though it manages two separate lists and two statics (universe and null). The first collection is an object pool...
2
3640
by: joe | last post by:
hi, after reading some articles and faq, i want to clarify myself what's correct(conform to standard) and what's not? or what should be correct but it isn't simply because compilers don't support. (first i compiled them with g++3.x. ERR means compiler will bark, otherwise it does accept it. Then the Comeau C/C++ 4.3.3 comes)
7
1843
by: Siemel Naran | last post by:
Hi. I have a function template <class InputIter, class OutputIter> void f(InputIter begin, InputIter end, OutputIter result); With c of type char* and cc of type const char*, the code f(c,c,cc) calls f<char*, const char *>, which is fine. But f(c,c,c) calls a new instantiation f<char*,char*> whereas I'd like it to call f<const char*,char*>.
3
1641
by: Sven Groot | last post by:
This was posted by someone in comp.lang.c++, and later in microsoft.public.vstudio.general, but since I know Carl is in this group, and he's the one that should read this, I've reposted it here. I've also minimalised the code that causes the bug. The bug is that the following syntax causes an Internal Compiler Error. The code is not correct, but should produce a warning or error message, not an ICE. It occurs when a template class...
3
1780
by: martin.druon | last post by:
Hi, I created a template class to represent hypermatrix. I would like to add methods where the number of parameters are checked during the compilation time. For example : template <size_t dim> class Matrix { protected :
2
2520
by: Lionel B | last post by:
I have a function which takes a functor argument. I which to call it for a functor which is actually a class member; this works fine, using the mem_fun_ref and bind1st functions (see listing 1 below). Or, rather, it works fine as long as my member functor is const. The problem comes when I wish to use it for a *non*-const functor (see listing 2 below): *** Start listing 1 *************************************************** // test1.cpp
26
4433
by: Turin | last post by:
Dear all; As far as I understand the idea behind getter methods, it is used to make sure that private memers of a class is returned appropriately to the calling object. However, if all I am interested in when making a member private is to disallow the modification of the value of that member (read-only member), then how about doing the following:
6
2410
by: .rhavin grobert | last post by:
hello;-) i frequently need the following construction: ReturnParam § Function() § { /...do something.../ someType var § = something; /...do something.../ return something;
0
9710
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
10593
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
10340
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
10329
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,...
1
7626
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3830
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3000
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.