0

I have a function template as this.

template<class T> T getFromString(const string& inStream)
{
    istringstream stream (inStream);
    T t;

    stream >> t;
    return t;
}

I am not getting how to use this function template. I have tried the usual method of using function template it was giving an error. Please let me know for getting out of this.

3 Answers 3

4

You can use it like this:

std::string a = "11";
int n = getFromString<int>(a);

This will extract the integer value from the string.

BTW, it is good to use T t = T(); inside the template as it will gurantee the initialization for the basic datatypes even if the extaction fails.

Sign up to request clarification or add additional context in comments.

Comments

1

Unleashing the power of Boost:

int n = boost::lexical_cast<int>("11");

2 Comments

while this is good advise, it does nothing to answer the question.
Not really, though you could note that the use is exactly the same. However I strongly believe in not reinventing the wheel, especially when lexical_cast is likely to be much faster for integral types because of careful tuning ;)
0

The problem is that the compiler cannot use the return type to infer the types of the function. You need to explicitly provide the type that you want as part of the function call, as @Naveen already mentioned: getFromString<int>("123"). Another approach is changing the function signature so that instead of returning it receives the type as an argument:

template <typename T>
void getFromString( const std::string & str, T & value ) { ... }
int main() {
   int x;
   getFromString("123",x);
}

As you provide a variable of type T in the call, the compiler is now able to infer the type from the arguments. (x is an int, so you are calling getFromString<int>). The disadvantage is that you need to create the variable in advance and user code will be more convoluted for simple use cases as int n = getFromString<int>( "123" );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.