Overloading by return value in C++

Posted on Posted in cpp, development, Uncategorized

Here we have a method that allows us to determine return parameter type using templates and operator overloading in C++. This is something that I needed for a project that I am working on where a method call would give me the expected type based on the return type.

Usage

There is two way of using this. First one is by calling the para method and second one is by invoking the conversion method directly parameter.
Personally, I prefer the first one as this one allows me to use it with auto keyword.


std::string p0   = param<std::string>(arguments, 0);
auto        p0_a = param<std::string>(arguments, 0);

int         p1   = param<int>(arguments, 1);
auto        p1_a = param<int>(arguments, 1);

// Invoking parameter conversion directly
std::string p0_p = parameter(arguments, 0); 
int         p1_p = parameter(arguments, 1);

Implemenation

struct parameter
{
	parameter(const CefV8ValueList & arguments, int index) 
		:_arg (arguments.at(index)) 
	{
	};
 
	operator std::string() { return _arg->GetStringValue().ToString(); }
	operator int() { return _arg->GetIntValue();}
	operator bool() { return _arg->GetBoolValue(); }
	operator double() { return _arg->GetDoubleValue();}
 
	CefRefPtr<CefV8Value> _arg;
};
 
template<typename T>
T param(const CefV8ValueList & arguments, int index)
{
	return parameter(arguments, index);
}

Reference :
http://en.cppreference.com/w/cpp/language/cast_operator

Leave a Reply

Your email address will not be published. Required fields are marked *