473,790 Members | 3,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

template function problem

Dear all,

I have the following code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int str_to_int (const string str)
{
istringstream str_s (str);
int num;
str_s >num;
return num;
}

template <typename T>
string num_to_str (const T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}

int main (void)
{
int i = 3, j = 5;
string str = num_to_str (j);
i += str_to_int (str);
cout << i << endl;
getchar();
return 0;
}

As you can see from the function "num_to_str ", it has been tested with
various numeric data types such as short, float, double, ..etc. and it
works just fine.
However, the function "str_to_int " can also be replaced with
"str_to_flo at", "str_to_dou ble" and so third and so fourth with just
replacing the int to float, int to double, ..etc.
So i thought of making it a template function as well and changed the
function "str_to_int " into:

template <typename T>
T str_to_num (const string str)
{
istringstream str_s (str);
T num;
str_s >num;
return num;
}
but i get the following error:
28 no matching function for call to `str_to_num(std ::string&)'

Can any one see what's wrong?

Oct 1 '06 #1
8 3059
In article <11************ **********@h48g 2000cwc.googleg roups.com>,
"coosa" <co*****@gmail. comwrote:
Dear all,

I have the following code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int str_to_int (const string str)
{
istringstream str_s (str);
int num;
str_s >num;
return num;
}

template <typename T>
string num_to_str (const T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}

int main (void)
{
int i = 3, j = 5;
string str = num_to_str (j);
i += str_to_int (str);
cout << i << endl;
getchar();
return 0;
}

As you can see from the function "num_to_str ", it has been tested with
various numeric data types such as short, float, double, ..etc. and it
works just fine.
However, the function "str_to_int " can also be replaced with
"str_to_flo at", "str_to_dou ble" and so third and so fourth with just
replacing the int to float, int to double, ..etc.
So i thought of making it a template function as well and changed the
function "str_to_int " into:

template <typename T>
T str_to_num (const string str)
{
istringstream str_s (str);
T num;
str_s >num;
return num;
}
but i get the following error:
28 no matching function for call to `str_to_num(std ::string&)'

Can any one see what's wrong?
You need to tell it, at the place it is being called, what type to
convert to. As in:

double d = str_to_num<doub le>( myString );

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Oct 1 '06 #2

Daniel T. wrote:
In article <11************ **********@h48g 2000cwc.googleg roups.com>,
"coosa" <co*****@gmail. comwrote:
Dear all,

I have the following code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int str_to_int (const string str)
{
istringstream str_s (str);
int num;
str_s >num;
return num;
}

template <typename T>
string num_to_str (const T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}

int main (void)
{
int i = 3, j = 5;
string str = num_to_str (j);
i += str_to_int (str);
cout << i << endl;
getchar();
return 0;
}

As you can see from the function "num_to_str ", it has been tested with
various numeric data types such as short, float, double, ..etc. and it
works just fine.
However, the function "str_to_int " can also be replaced with
"str_to_flo at", "str_to_dou ble" and so third and so fourth with just
replacing the int to float, int to double, ..etc.
So i thought of making it a template function as well and changed the
function "str_to_int " into:

template <typename T>
T str_to_num (const string str)
{
istringstream str_s (str);
T num;
str_s >num;
return num;
}
but i get the following error:
28 no matching function for call to `str_to_num(std ::string&)'

Can any one see what's wrong?

You need to tell it, at the place it is being called, what type to
convert to. As in:

double d = str_to_num<doub le>( myString );

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer have anyone to discuss your doubts with,
nor any ability to discuss them.
Thanks alot, it worked; i just thought that specifying the type is only
required by class templates and not function templates!

Oct 1 '06 #3
Daniel T. wrote:
In article <11************ **********@h48g 2000cwc.googleg roups.com>,
"coosa" <co*****@gmail. comwrote:
Dear all,

I have the following code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int str_to_int (const string str)
{
istringstream str_s (str);
int num;
str_s >num;
return num;
}

template <typename T>
string num_to_str (const T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}

int main (void)
{
int i = 3, j = 5;
string str = num_to_str (j);
i += str_to_int (str);
cout << i << endl;
getchar();
return 0;
}

As you can see from the function "num_to_str ", it has been tested with
various numeric data types such as short, float, double, ..etc. and it
works just fine.
However, the function "str_to_int " can also be replaced with
"str_to_flo at", "str_to_dou ble" and so third and so fourth with just
replacing the int to float, int to double, ..etc.
So i thought of making it a template function as well and changed the
function "str_to_int " into:

template <typename T>
T str_to_num (const string str)
{
istringstream str_s (str);
T num;
str_s >num;
return num;
}
but i get the following error:
28 no matching function for call to `str_to_num(std ::string&)'

Can any one see what's wrong?

You need to tell it, at the place it is being called, what type to
convert to. As in:

double d = str_to_num<doub le>( myString );

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer have anyone to discuss your doubts with,
nor any ability to discuss them.
By the way, shouldn't the same apply to the function "num_to_str " as:
string str = num_to_str <int(j); ?
but it works fine with: string str = num_to_str (j);

Oct 1 '06 #4
"coosa" <co*****@gmail. comwrote:
By the way, shouldn't the same apply to the function "num_to_str " as:
string str = num_to_str <int(j); ?
but it works fine with: string str = num_to_str (j);
No, the same doesn't apply because the compiler can infer the type by
looking at the parameter's type.

You could set your function up like iostream's op>and then you
wouldn't have to specify the type.

template < typename T >
void string_to_num( const string& str, T& num )
{
//...
}

Now you would call it like:

double d;
string_to_num( myString, d );

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Oct 1 '06 #5

Daniel T. wrote:
"coosa" <co*****@gmail. comwrote:
By the way, shouldn't the same apply to the function "num_to_str " as:
string str = num_to_str <int(j); ?
but it works fine with: string str = num_to_str (j);

No, the same doesn't apply because the compiler can infer the type by
looking at the parameter's type.

You could set your function up like iostream's op>and then you
wouldn't have to specify the type.

template < typename T >
void string_to_num( const string& str, T& num )
{
//...
}

Now you would call it like:

double d;
string_to_num( myString, d );

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer have anyone to discuss your doubts with,
nor any ability to discuss them.
Ok Daniel,
Thanks for the help so far; I'd like to disturb you a little more! :-)
Have a look at this header file:

//Begin of File converter.hpp
#ifndef converterHPP
#define converterHPP

#include <iostream>

using namespace std;

namespace convert
{
class string
{
public:
template <typename T>
static T to_number (string);
};

class number
{
public:
template <typename T>
static string to_string (T);
};
}

#endif
//End of File converter.hpp

and then at this source file:

//Begin of File converter.cpp
#include "converter. hpp"
#include <sstream>

using namespace std;

namespace convert
{
template <typename T>
T string::to_numb er (string str)
{
T num;
istringstream str_s (str);
str_s >num;
return num;
}

template <typename T>
string number::to_stri ng (T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}
}
//End of File converter.cpp

and finally at this mail file:

//Begin of File main.cpp
#include "converter. hpp"
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
float f1 = 3.4;
int i1 = 5;
string s1 = "7.023";
double d1 = 12345.80346;
float f2 = convert::string ::to_number <float(s1); // causes error
string s2 = convert::number ::to_string <double(d1); //causes
error
system("PAUSE") ;
return EXIT_SUCCESS;
}
//End of File main.cpp

I get the folllowing error log

Compiler: Default compiler
Building Makefile: "C:\Dokumen te und
Einstellungen\A dministrator\De sktop\test3\Mak efile.win"
Executing make...
make.exe -f "C:\Dokumen te und
Einstellungen\A dministrator\De sktop\test3\Mak efile.win" all
g++.exe -D__DEBUG__ -c main.cpp -o main.o
-I"C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include"
-I"C:/Dev-Cpp/include/c++/3.4.2/backward"
-I"C:/Dev-Cpp/include/c++/3.4.2/mingw32"
-I"C:/Dev-Cpp/include/c++/3.4.2" -I"C:/Dev-Cpp/include" -g3

main.cpp: In function `int main(int, char**)':

main.cpp:14: error: no matching function for call to
`convert::strin g::to_number(st d::string&)'
converter.hpp:1 4: note: candidates are: static T
convert::string ::to_number(con vert::string) [with T = float]

main.cpp:15: error: conversion from `convert::strin g' to non-scalar
type `std::basic_str ing<char, std::char_trait s<char>,
std::allocator< char' requested

make.exe: *** [main.o] Error 1

Execution terminated

Could you please check it out and tell me what's wrong in the code?

Best regards

Oct 1 '06 #6
coosa schrieb:
Have a look at this header file:

//Begin of File converter.hpp
#ifndef converterHPP
#define converterHPP

#include <iostream>

using namespace std;

namespace convert
{
class string
{
public:
template <typename T>
static T to_number (string);
};

class number
{
public:
template <typename T>
static string to_string (T);
};
}
The problem is, that you declare a class named string and use a string as
parameter, which should be std::string but instead refers to your string class.

So my advice:
1) _never_ put "using namespace std;" in a header file.
2) don't name your own classes like standard library classes.

Make it string_to_numbe r() or just toString() and fromString().

Also, take a look at the FAQ:
http://www.parashift.com/c++-faq-lit...al-issues.html

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Oct 1 '06 #7
"coosa" <co*****@gmail. comwrote:

The error in your code has to do with the 'string' class you have
created in your header file. You are using std::string in your main
function, but convert::string in your 'convert' namespace.

Notes in the code:
Ok Daniel,
Thanks for the help so far; I'd like to disturb you a little more! :-)
Have a look at this header file:

//Begin of File converter.hpp
#ifndef converterHPP
#define converterHPP

#include <iostream>

using namespace std;
Don't put using declarations in headers, qualify each name instead.
>
namespace convert
{
class string
{
public:
template <typename T>
static T to_number (string);
};
Above you created your own string class "convert::strin g". Now the
compiler is assuming that any reference to "string" within this
namespace is really a reference to "convert::strin g" and not
"std::strin g".

Also, templated functions should be defined in the header file so the
definition is available at all points of use.
class number
{
public:
template <typename T>
static string to_string (T);
};
Above you created a class called 'number'. I get the impression you are
coming from Java? You don't need to put static functions inside classes.
}

#endif
//End of File converter.hpp
Try this for a header file instead:

#ifndef converterHPP
#define converterHPP

#include <iostream>

template < typename T >
T to_number( const std::string& s ) {
T result;
std::istringstr eam iss( s );
iss >result; // what if this fails?
// Currently the result will be undefined.
return result;
}

template < typename T >
std::string to_string( const T& val ) {
std::string result;
std::ostringstr eam oss;
oss << val; // what if this fails?
return oss.str();
}

#endif // converterHPP
and then at this source file:

//Begin of File converter.cpp
#include "converter. hpp"
#include <sstream>

using namespace std;

namespace convert
{
template <typename T>
T string::to_numb er (string str)
{
T num;
istringstream str_s (str);
str_s >num;
return num;
}

template <typename T>
string number::to_stri ng (T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}
}
//End of File converter.cpp
The above assumes convert::string for both references to 'string'. Your
code won't work with std::string as a result.
and finally at this mail file:

//Begin of File main.cpp
#include "converter. hpp"
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
float f1 = 3.4;
int i1 = 5;
string s1 = "7.023";
double d1 = 12345.80346;
float f2 = convert::string ::to_number <float(s1); // causes error
Your attempting to pass in a std::string instead of a convert::string .
string s2 = convert::number ::to_string <double(d1); //causes
error
Your attempting to assign a convert::string to a std::string, but have
defined no way to do that.
system("PAUSE") ;
return EXIT_SUCCESS;
}
//End of File main.cpp

I get the folllowing error log

main.cpp:14: error: no matching function for call to
`convert::strin g::to_number(st d::string&)'
The compiler can't find the above function, because one doesn't exist.
converter.hpp:1 4: note: candidates are: static T
convert::string ::to_number(con vert::string) [with T = float]
The above is what you do have (note "convert::strin g" inside the parens
instead of "std::strin g".)
main.cpp:15: error: conversion from `convert::strin g' to non-scalar
type `std::basic_str ing<char, std::char_trait s<char>,
std::allocator< char' requested
And here, the compiler says you are trying to convert from a
"convert::strin g" to a "std::strin g" (which is a typedef for
"std::basic_str ing<char, std::char_trait s<char>, std::allocator< char.)

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Oct 1 '06 #8

Daniel T. wrote:
"coosa" <co*****@gmail. comwrote:

The error in your code has to do with the 'string' class you have
created in your header file. You are using std::string in your main
function, but convert::string in your 'convert' namespace.

Notes in the code:
Ok Daniel,
Thanks for the help so far; I'd like to disturb you a little more! :-)
Have a look at this header file:

//Begin of File converter.hpp
#ifndef converterHPP
#define converterHPP

#include <iostream>

using namespace std;

Don't put using declarations in headers, qualify each name instead.

namespace convert
{
class string
{
public:
template <typename T>
static T to_number (string);
};

Above you created your own string class "convert::strin g". Now the
compiler is assuming that any reference to "string" within this
namespace is really a reference to "convert::strin g" and not
"std::strin g".

Also, templated functions should be defined in the header file so the
definition is available at all points of use.
class number
{
public:
template <typename T>
static string to_string (T);
};

Above you created a class called 'number'. I get the impression you are
coming from Java? You don't need to put static functions inside classes.
}

#endif
//End of File converter.hpp

Try this for a header file instead:

#ifndef converterHPP
#define converterHPP

#include <iostream>

template < typename T >
T to_number( const std::string& s ) {
T result;
std::istringstr eam iss( s );
iss >result; // what if this fails?
// Currently the result will be undefined.
return result;
}

template < typename T >
std::string to_string( const T& val ) {
std::string result;
std::ostringstr eam oss;
oss << val; // what if this fails?
return oss.str();
}

#endif // converterHPP
and then at this source file:

//Begin of File converter.cpp
#include "converter. hpp"
#include <sstream>

using namespace std;

namespace convert
{
template <typename T>
T string::to_numb er (string str)
{
T num;
istringstream str_s (str);
str_s >num;
return num;
}

template <typename T>
string number::to_stri ng (T num)
{
ostringstream o_str;
o_str << num;
return o_str.str();
}
}
//End of File converter.cpp

The above assumes convert::string for both references to 'string'. Your
code won't work with std::string as a result.
and finally at this mail file:

//Begin of File main.cpp
#include "converter. hpp"
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
float f1 = 3.4;
int i1 = 5;
string s1 = "7.023";
double d1 = 12345.80346;
float f2 = convert::string ::to_number <float(s1); // causes error

Your attempting to pass in a std::string instead of a convert::string .
string s2 = convert::number ::to_string <double(d1); //causes
error

Your attempting to assign a convert::string to a std::string, but have
defined no way to do that.
system("PAUSE") ;
return EXIT_SUCCESS;
}
//End of File main.cpp

I get the folllowing error log

main.cpp:14: error: no matching function for call to
`convert::strin g::to_number(st d::string&)'

The compiler can't find the above function, because one doesn't exist.
converter.hpp:1 4: note: candidates are: static T
convert::string ::to_number(con vert::string) [with T = float]

The above is what you do have (note "convert::strin g" inside the parens
instead of "std::strin g".)
main.cpp:15: error: conversion from `convert::strin g' to non-scalar
type `std::basic_str ing<char, std::char_trait s<char>,
std::allocator< char' requested

And here, the compiler says you are trying to convert from a
"convert::strin g" to a "std::strin g" (which is a typedef for
"std::basic_str ing<char, std::char_trait s<char>, std::allocator< char.)

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer have anyone to discuss your doubts with,
nor any ability to discuss them.
Thanks alot, that was very helpful,

I do like java alot indeed, but i started learning C++ before Java;
it's just that i didn't tough C++ for quite some time, so my brain have
got rusted! :-)

Oct 1 '06 #9

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

Similar topics

4
2610
by: C. Carbonera | last post by:
/* Hi, I have a problem with explicit instantiation of templates in Visual C++ 6.0. I have provided the source below. I have an example of a function template that produces incorrect output in the code below. The function template < typename T >
0
1645
by: Chris F Clark | last post by:
In our C++ project we have some internal bug reporting macros that we use to get useful information when the program does something unexpected. Essentially at the point of the error, we invoke an internal interactive debugger that knows the classes within our system and allow us to walk around the objects that exist at the time of the fault. It mostly works fairly well. That catch being that we have to hand implement some of the code...
4
2343
by: Thomi Richards | last post by:
Hi, I'm trying to create a simple stack class using C++ and templates. Everything works well and good if I amke the class totally inline. However, as soon as I try to seperate the class into a .h and a .cpp file, gcc throws some strange linking errors. Compiling like this:
7
2133
by: Lionel B | last post by:
Greetings. The following code compiles ok and does what I'd expect it to do: ---------- START CODE ---------- // test.cpp
3
3940
by: Chris | last post by:
I am having a very strange problem involving virtual functions in template classes. First of all, here is an extremely simplified structure of the two classes I am having problems with. template<class Type> class base { public: base& operator/=(const base&); Type *image;
7
354
by: hopangtsun | last post by:
Hi all, I have encountered a problem on using the function template my goal is to add two numbers, which they can be int or double if I do this in this way template<class T> T addition(T a, T b){ return (a + b); } it can only deal with int + int or double + double however, I also want int + double, double + int so I come up with this idea template<class T , class U> T addition(T a, U b){ return (a+b); } this created a...
19
7941
by: aaragon | last post by:
Hi everyone. A very simple question. I would like to know what is better in terms of performance. I want to use a simple function to obtain the minimum of two values. One way could be using a macro: #define min(a,b) ((a<b)?a:b) I thought that another way could be to use a template function: template <class T> T min<T a, T b>
3
3759
by: Hamilton Woods | last post by:
Diehards, I developed a template matrix class back around 1992 using Borland C++ 4.5 (ancestor of C++ Builder) and haven't touched it until a few days ago. I pulled it from the freezer and thawed it out. I built a console app using Microsoft Visual C++ 6 (VC++) and it worked great. Only one line in the header file had to be commented out. I built a console app using Borland C++ Builder 5. The linker complained of references to...
5
1746
by: krishnaroskin | last post by:
Hey all, I've been running into a problem with default values to template'd functions. I've boiled down my problem to this simple example code: #include<iostream> using namespace std; // function object
3
2923
by: toton | last post by:
Hi, I want to specialize template member function of a template class . It is creating some syntax problem .... Can anyone say how to do it ? The class is something like this template<typename T,typename Alloc = std::allocator<T class CircularBuffer4 { public: typedef typename CircularBuffer<T,Alloc>::size_type
0
9666
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
9512
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
10419
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
10147
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
9023
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7531
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
6770
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();...
1
4100
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
3
2910
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.