Click here to Skip to main content
15,742,357 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Consider this code, compiled with g++ v.4.8.1-4 in Code::Blocks 10.05:

#include <stdexcept>
#include <sstream>
#include <string>

// Class: my_traits_type
struct my_traits_type : public std::char_traits<char>

// Class: my_string_type
using my_string_type=std::basic_string<char, my_traits_type>;

// Converts a std::basic_string<> into a T type.
template <typename T, typename CharT, typename Traits, typename Alloc>
T To(const std::basic_string<CharT, Traits, Alloc>& s)
	T value;

	std::basic_istringstream<CharT, Traits, Alloc> is(s);

	is >> value;

	if(!(is && (is >> std::ws).eof()))
	    throw std::invalid_argument("Function: To<>. Unallowed conversion.");

	return value;


and this simple main() function:
#include <iostream>
#include <string>
#include "error_sample.h"

int main()
	size_t value=0;

	std::string str_1("1");


	std::cout << value << std::endl; // Prints 1.

	my_string_type my_string("1");

	value=To<size_t>(my_string); // Ouch! invalid_argument exception thrown.

	std::cout << value << std::endl;

	return 0;

If we now inspect into:
is >> value;
, we discover value equals to 2293515, in my case.

Can anybody explain what's going on here?

Thanks in advance.
Pablo Aliskevicius 13-Nov-13 7:18am    
What happens if you try this?

David Serrano Martínez 13-Nov-13 7:22am    
Checked. Exacty the same. Template parameters are correctly resolved.
CPallini 13-Nov-13 7:59am    
It works fine with Visual C++ 2010 Express, provided you change the 'undigestible' (the compiler is a bit dated) using with the equivalent typedef.
David Serrano Martínez 13-Nov-13 8:06am    
Thanks. After replacing "using" with "typedef", the (bad) behavior is the same. Maybe it could be a problem with g++ v.4.8.1-4.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900