We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,668 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

template function can't be called without determination of Type

Hey daniweb, I stumbled upon an issue I can't solve myself.
Here is the code :

#include <sstream>
#include <iostream>

template <class T>
inline T htot(std::string str)
{
    T x;
    std::stringstream ss;

    ss << std::hex << str;
    ss >> x;

    return x;
}

int main()
{
    int x = htot("0x0F");           // error: no matching function for call to 'htot(const char [5])'|

    std::cout << "Hex(F) is Dec(" << x << ")";
    std::cin.get();

    return 0;
}

So why can't the compiler do this job without specifying the type with the call?
For example when I do specify the type with the call it compiles just fine
Call me dumb, but I just wasted 2 hours finding solutions to this.

Any help would be appreciated !
(My setup : GCC(MinGW) 4.4.1 on Win7)

2
Contributors
2
Replies
1 Hour
Discussion Span
8 Months Ago
Last Updated
3
Views
Question
Answered
Dman01
Light Poster
30 posts since Aug 2010
Reputation Points: 20
Solved Threads: 3
Skill Endorsements: 0

I think you have to specify the type T. Template functions, I believe, can only deduce what T is based on the arguments passed.

The compiler does not know if you want to return an integer or float based on having std::string as an argument, for example.

int x = htot<int>("0x0F");

dx9_programmer
Junior Poster in Training
61 posts since Mar 2011
Reputation Points: 22
Solved Threads: 12
Skill Endorsements: 0

Ah ok, I guess the function call is proceeded before the assignment, should've known that.
Apparently the most basic errors are the most irritating ones and I don't check them ? Thanks, you saved me!

Dman01
Light Poster
30 posts since Aug 2010
Reputation Points: 20
Solved Threads: 3
Skill Endorsements: 0
Question Answered as of 8 Months Ago by dx9_programmer

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0620 seconds using 2.69MB