Ahmed Mazher
Ahmed Mazher

Reputation: 43

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

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;
}

Upvotes: 1

Views: 135

Answers (2)

Ahmed Mazher
Ahmed Mazher

Reputation: 43

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;
}

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

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");

Upvotes: 5

Related Questions