C++ does not directly support names parameters a.k.a. (Python) keyword arguments.
Possibly you just want the ability to specify argument values, nothing more. I suspect that, because you're attempting to store a floating point value 6.7
in an int
, which indicates that you're very new to programming. If that's all you want to, namely specify argument values, then you can use ordinary positional arguments, like this:
#include <iostream>
using namespace std;
auto add2var( int const a, int const b )
-> int
{ return a + b; }
auto main() -> int
{
int const c = add2var( 5, 6 );
cout << c << endl;
}
Note that there's no stdafx.h
here.
In a Visual Studio project turn off precompiled header support in the project settings in order to make compile without stdafx.h
, compile.
If you really want to have named arguments For simple cases like the one presented you can use the named parameters idiom a.k.a. NMI. Essentially NMI consists in defining an arguments structure with chainable setters and default values. It's described in the C++ FAQ.
#include <iostream>
struct Args_add2var
{
int a_ = 0;
int b_ = 0;
auto a( int const value )
-> Args_add2var&
{ a_ = value; return *this; }
auto b( int const value )
-> Args_add2var&
{ b_ = value; return *this; }
};
auto add2var( Args_add2var const& args )
-> int
{ return args.a_ + args.b_; }
auto main() -> int
{
using Args = Args_add2var;
int const c = add2var( Args().a( 5 ).b( 6 ) );
using namespace std;
cout << c << endl;
}
For a more general but restricted and IMHO pretty awkward solution, check out the Boost Parameters sub-library. Essentially the idea there is to declare global objects with the names of the parameters, to support the initialization-in-call notation. That's one issue that makes the scheme awkward, and as I recall it also has problems with constructors.
#include <boost/parameter.hpp>
#include <iostream>
using namespace std;
BOOST_PARAMETER_NAME( a )
BOOST_PARAMETER_NAME( b )
BOOST_PARAMETER_FUNCTION(
(int), // 1. parenthesized return type
add2var, // 2. name of the function template
tag, // 3. namespace of tag types, "tag" used by macro above
(optional // 4. two optional parameters, with defaults
(a, (int), 0)
(b, (int), 0)
)
)
{ return a + b; }
auto main() -> int
{
int const c = add2var( _a = 5, _b = 6 );
cout << c << endl;
}
Note that e.g. _a
is not a global int
variable, rather it's a global variable that represents the argument name.
In more general code it would be placed in a namespace along with the function.
For a more general discussion see my 2010 DDJ article "Pure C++ Options Classes". It does however suffer from Very Bad Formatting (it was nice as submitted), and the code is C++03. I would do things much more cleanly in C++11, but haven't looked at it since.