boom
boom

Reputation: 6166

Function template

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.

Upvotes: 0

Views: 257

Answers (3)

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

Upvotes: 0

Matthieu M.
Matthieu M.

Reputation: 299850

Unleashing the power of Boost:

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

Upvotes: 1

Naveen
Naveen

Reputation: 73443

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.

Upvotes: 4

Related Questions