Opened 12 years ago

Closed 11 years ago

Last modified 11 years ago

#4397 closed Feature Requests (fixed)

specialization for lexical_cas for identical Target and Source types

Reported by: alexey.kutumov@… Owned by: Antony Polukhin
Milestone: Boost 1.44.0 Component: lexical_cast
Version: Boost 1.44.0 Severity: Optimization
Keywords: lexical_cast specialization Cc: alexey.kutumov@…

Description

std::string s1 = "str"; std::string result = boost::lexical_cast<std::string>(s1);

In this case it is possible to use specialization of lexical_cast which just returns input arg.

I created simple example with specialization of lexical_cast:

#include <boost/cstdint.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/type_traits.hpp>
#include <iostream>

template <typename Target, typename Source, bool val> struct helper
{
	/// Default action is to use lexical_cast
	static Target get(const Source & src)
	{
		return boost::lexical_cast<Target>(src);
	}
};

template <typename Target, typename Source> struct helper<Target, Source, true>
{

	/// Use this if Target and Source identical
	static Target get(const Source & src)
	{
		return src;
	}
};

template <typename Target, typename Source> Target my_lexical_cast(const Source & res)
{
	/// Use boost::is_same for checking identity of Target and Source
	return helper<Target, Source, boost::is_same<Target, Source>::value>::get(res);
}

int main(int argc, char * argv[])
{
	std::string b1 = "10";

	std::string b2 = my_lexical_cast<std::string>(b1);
	int b3 = my_lexical_cast<int>(b1);

	std::cout << "b1: " << b1 << std::endl;
	std::cout << "b2: " << b2 << std::endl;
	std::cout << "b3: " << b3 << std::endl;

	return 0;
}

This code checked in msvc 9.0, mingw32-g++ 4.4.0

Attachments (1)

conv_test.cpp (2.3 KB ) - added by alexey.kutumov@… 12 years ago.
Simple test for performance of specialization of lexical_cast

Download all attachments as: .zip

Change History (5)

by alexey.kutumov@…, 12 years ago

Attachment: conv_test.cpp added

Simple test for performance of specialization of lexical_cast

comment:1 by alexey.kutumov@…, 12 years ago

I compiled given test under msvc 2008, and my_lexical_cast is two times faster then usual boost::lexical_cast

comment:2 by Antony Polukhin, 11 years ago

Owner: changed from nasonov to Antony Polukhin
Status: newassigned

comment:3 by Antony Polukhin, 11 years ago

Resolution: fixed
Status: assignedclosed

(In [71958]) Fixes #5350. Fixes #4397 More tests (for conversions to float types, for conversions of negative values to unsigned integers)

Last edited 11 years ago by Antony Polukhin (previous) (diff)

comment:4 by Antony Polukhin, 11 years ago

Thanks for the idea.
It was redesigned and implemented in #5350, #5350 was merged to trunk (with some fixes for behavior described in #5494 and more optimizations for conversions from arithmetic to arithmetic types).

Last edited 11 years ago by Antony Polukhin (previous) (diff)
Note: See TracTickets for help on using tickets.