Why my template function is not a valid match in this call? - c++

i made the following code to convert number to string and reverse
in the commented part of code i want to make the function type a template
thinking that it will acquire the type according to context "e.g if i assign
it to int variable the function will be of type int " but this not occur and compiler
give error message
D:\computer science\project\stringToint.cpp In function 'int main()':
49 25 D:\computer science\project\stringToint.cpp [Error] no matching function for call to 'intstr(const char [10])'
49 25 D:\computer science\project\stringToint.cpp [Error] candidate is:
17 21 D:\computer science\project\stringToint.cpp template<class T> T intstr(std::string)
i think that their was error in using stringstream object
but i was successful in achieving the function to work if
i specify the type of function but this will make me write
different function for every type
is i miss understand some thing please help
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
template<typename T>
string strint (T oty)
{
string ity;
stringstream ss;
ss<<oty;
ss>>ity;
return ity;
}
/*
template<typename T>
T intstr (string oty)
{
T ity;
stringstream ss;
ss<<oty;
ss>>ity;
return ity;
}
*/
int intstr (string oty)
{
int ity;
stringstream ss;
ss<<oty;
ss>>ity;
return ity;
}
signed char charstr (string oty)
{
signed char ity;
stringstream ss;
ss<<oty;
ss>>ity;
return ity;
}
int main()
{
int i;
signed char c;
string s;
s=strint(123);
cout<<s<<endl;
i=intstr("123456789");
cout<<i<<endl;
c=charstr("2");
cout<<c;
return 0;
}

You should explicitly specify template parameter for function, since compiler can't deduce T, because there are no parameters of type T in function args. Like
intstr<int>("123456789");

thanks #ForEveR i now reduced my code to look like this and it is working well
i hope it is the best solution of converting number to string and vise verse
using stringstream
thanks alot
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
template<typename T1,typename T2>
T2 strint (T1 oty)
{
T2 ity;
stringstream ss;
ss<<oty;
ss>>ity;
return ity;
}
int main()
{
cout<< strint <string,int>("1234") <<endl;
cout<< strint <int,string>(456) <<endl;
cout<< strint <string,float>("3.14") <<endl;
cout<< strint <string,char>("3") <<endl;
return 0;
}

Related

While I am passing an string to a void function whose argument is a character pointer its't working.Again I'm passing f("Nayem") it wroks,atleast doe

While I am passing an string to a void function(string s="nayem"; f(s);) whose argument is a character pointer its't working.Again I'm passing f("Nayem") it wroks,atleast compilation is ok,why this?
#include<bits/stdc++.h>
using namespace std;
void f(char* p)
{
cout<<p<<endl;
}
int main()
{
string s="NAYEM";
f(s);//not working
//but f("nayem"); this compiles
cout<<s<<endl;
return 0;
}

passing a stringstream to a function

I'm trying to pass a stringstream, from a file, to a function. When I'm calling the template function, I'm getting an error: no matching function for call to 'toFile'. I verified that the life is opened and the data has passed from it to the stringstream.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
template <typename T1>
void toFile(string type, int NumOfElements, stringstream& ss){
T1* myArray = new T1[NumOfElements]; // declaring new array to store the elements
int value;
for(int i = 0; i < NumOfElements; i++){ // store the elements in the array
ss >> value;
myArray[i] = value;
cout << myArray[i] << " ";
}
}
int main(int argc, char *argv[])
{
ifstream ins;
ofstream outs;
string strg1;
string type;
int NumOfElements = 0;
stringstream inputString;
ins.open(argv[1]);
if(argc<1) {
cout << "please provide the file path." << endl;
exit(1);
}
while (getline(ins, strg1)){ // reading line from the file
inputString.clear(); // clearing the inputString before reading a new line
inputString << strg1;
inputString >> type ; // reading 1st element in a row
inputString >> NumOfElements; // reading 2nd element in a row
toFile(type, NumOfElements, inputString);
}
ins.close();
return 0;
}
toFile is a function template, so it can only be called with a template parameter. Sometimes function templates can deduce their parameters from their arguments, but since T1 isn't used in your argument list, there's no way to deduce it. You'll need to explicitly provide the template argument instead, for example:
toFile<int>(type, NumOfElements, inputString);
You didn't specify a template argument for toFile, so the template cannot be instantiated.
Thus, no function toFile<T> (which would have been an instantiation of said template) exists.
The argument cannot be deduced automatically because none of the function arguments have anything to do with it.

Error with Converting Struct

I am trying to read in a huge data set of lastnames firstnames and ssn's. When I try to point to my struct it says it is trying to convert my single_info struct from individualf to singleinfo ...
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
struct single_info {
string firstnames[6000];
string lastnames[6000];
string socialsecurity[6000];
double gpa;
};
void ScanInFile(istream &, struct single_info, int *total);
void Outputfile(ostream &, struct single_info, int *total);
Here is my struct
Here are my functions and for some reason I get error: could not convert ‘& individualf’ from ‘single_info*’ to ‘single_info’
void ScanInFile(istream &inputfile, struct single_info *individualf, int *total)
{
int i=0;
while(!inputfile.eof()){
inputfile >> individualf->socialsecurity[i];
inputfile >> individualf->firstnames[i];
inputfile >> individualf->lastnames[i];
i++
}
*total = i;
}
void Outputfile(ostream &outputfile, struct single_info *individualf, int *total)
{
for(int i=0; i < *total; i++){
outputfile << individualf->socialsecurity[i];
outputfile << individualf->firstnames[i];
outputfile << individual->lastnames[i];
}
outputfile << endl;
}
The problem is that the declarations of ScanInFile and Outputfile say that they take a struct single_info as their parameter type. It looks like you meant for that to be struct single_info* (which would match your definitions). Whatever code is attempting to call your functions can only see the declarations and is trying to pass a single_info* even though it asks for just a single_info.
Note that putting struct before a struct identifier is unnecessary in C++.
Yes it's the prototype. It needs to be defined exactly like the function itself.

Using template in c++ - Returning values from method

I wanna a method that receives a generic type, and a generic type (that's defined in run time). In the example there's if I'm using a string type, It needs to return the first param lenght (in string); If I'm using a int type, needs to return the biggest (int integer).
Have a look:
#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <conio.h>
#include <sstream>
#include <string>
#include <atldbcli.h>
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
using namespace std;
class Test
{
public:
template<class T>
T returnVal(T valueOne, T valueTwo);
};
template<class T>
T Test::returnVal(T valueOne, T valueTwo)
{
if(typeid(valueOne) == typeid(string))
{
string teste = valueOne;
int testeInt = teste.size();
ostringstream testeString;
testeString << testeInt;
teste = testeString.str();
return teste;
}
else
return valueOne > valueTwo? valueOne:valueTwo;
}
int main()
{
string reference = "stringVal";
Test ref;
cout << ref.returnVal<string>(reference, "asasas") << endl;
cout << ref.returnVal<int>(10, 485);
getch();
return 0;
}
However, when the main function calls ref.returnVal(10, 485); it's show a message error: 'return' : cannot convert from 'std::string' to 'int'
Does anybody know what's wrong?
Thanks
this is not the proper way to do what you want. You can't use typeid to switch between types and do different operations, because all the different paths still have to be compiled, and inside your if you do return a string while your method returns an int.
google template specialization, that's what you need I guess...
#include <string>
template <class T>
int returnVal(T valueOne, T valueTwo);
template <>
int returnVal<std::string>(std::string valueOne, std::string valueTwo)
{
return (int)valueOne.length();
}
template <>
int returnVal<int>(int valueOne, int valueTwo)
{
return std::max(valueOne, valueTwo);
}
int main()
{
int x = returnVal(std::string("Hello"), std::string("World!"));
int y = returnVal(1,2);
return 0;
}
Unless I'm misunderstanding you, you could achieve this with template specialization?
All previous answers clearly identify the problem. As for a better way to do it:
class Test
{
public:
string returnVal(string valueOne, string valueTwo)
{
string teste = valueOne;
int testeInt = teste.size();
ostringstream testeString;
testeString << testeInt;
teste = testeString.str();
return teste;
}
int returnVal(int valueOne, int valueTwo)
{
return valueOne > valueTwo? valueOne:valueTwo;
}
};
If you instantiate your template for type int, it looks like this:
int Test::returnVal(int valueOne, int valueTwo)
{
if(typeid(valueOne) == typeid(string)) // This will be false
{
string teste = valueOne;
int testeInt = teste.size();
ostringstream testeString;
testeString << testeInt;
teste = testeString.str();
return teste;
}
else
return valueOne > valueTwo? valueOne:valueTwo;
}
The problem is that the then-clause of your if returns a string even though the return type of the function is int. The fact that the then-clause will never execute because typeif(valueOne) can't possible be string doesn't matter because the type checker does not care about that. All he sees is a return statement that returns a string, so that's an error.
To do what you want, you should simply overload your function for strings and remove all the string-specific code from the templated function.

Why does my specialized template function 'OverloadedFunk' give "could not be resolved" error in C++?

So I've been trying to figure out how to use template specialization but ran into an unexpected compiler error. The more I check the syntax the more it looks correct so clearly I'm missing something. All I'm trying to do is create two function templates that are specialized and compare them to overloaded functions. The error I get is as follows: 'OverloadedFunk' could not be resolved on line 28 and 35. Here is the code I trying to rock:
#include <iostream>
using namespace std;
enum ErrorCode {
ERROR_NONE = 0, ///< No errors
SOME_FAILURE_01,
SOME_FAILURE_02,
INVALID_STATUS,
ERROR_UNKNOWN,
};
template<typename _to, typename _from>
inline int OverLoadedFunk(_from const &arg, _to &dest)
{
cout << "OverLoadedFunk3 - Template to from";
return 0;
}
template<>
inline int OverloadedFunk(const int &from, std::string &dest) //Line 28
{
cout << "OverloadedFunk1 - int to string";
return 0;
}
template<>
inline int OverloadedFunk(const ErrorCode &from, std::string &dest) //Line 35
{
cout << "OverloadedFunk2 - enumeration to string";
return 0;
}
int main() {
std::string localDest = "test";
int localFrom = 1234;
OverloadedFunk(localFrom, localDest);
return 0;
}
What exactly am I doing wrong here? I know I could use overloaded functions instead, but I'm trying to test difference between specialization and overloaded functions so that won't help me in this case. All help is greatly appreciated.
Your primary function template is named OverLoadedFunk, but your specializations are named OverloadedFunk – C++ is case-sensitive!