"named parameters mechanism"

A

Adam Hartshorne

What is named parameter mechanism? Any ideas? I am looking through some
code and there is a comment saying "VC++ has trouble with the named
parameters mechanism", which i have no idea what this means.

Any help much appreciated,

Adam
 
J

John Carson

Adam Hartshorne said:
What is named parameter mechanism? Any ideas? I am looking through
some code and there is a comment saying "VC++ has trouble with the
named parameters mechanism", which i have no idea what this means.

Any help much appreciated,

Adam

Consider a standard C++ function:

void foo(int x, int * ptr)
{
//stuff
}

If you call the function with

foo(a, b);

then a is treated as an int, and b is treated as a int *, in accordance with
the function declaration, i.e., the order in which arguments are supplied
strictly determines the way in which they are interpreted. The first has to
be an int and the second has to be an int*.

With named parameters, by contrast, there is a syntax available whereby you
can specify the type of the function arguments that you supply, thus giving
freedom in the order in which arguments are entered.

Since C++ does not support named parameters, except with elaborate
workarounds, the comment either refers to such workarounds or to something
completely different. I suspect it might be the latter (in which case the
phrase is being misapplied).

I suspect that the comment actually means is that VC++ 6 doesn't cope well
with the following situation:

#include <iostream>
using namespace std;


struct A
{
A()
{cout << "This is A\n"; }
};


struct B
{
B()
{cout << "This is B\n"; }
};

template <class T>
void foo()
{
T t;
}


int main()
{
foo<A>();
foo<B>();

return 0;
}

Here you will note that the template parameter T is not used as a type in
declaring foo's function parameters, i.e., we don't have, say,

template <class T>
void foo(T t)
{}

Accordingly, template parameters cannot be deduced from the function
arguments supplied. This means you must distinguish different instantiations
of the template by explicitly *naming* the template argument, as in foo<A>()
and foo<B>().

You will note if you run the code on VC++ 6 that it gets it wrong and the
output is

"This is B";

both times.

The workaround is to always use template parameters in the list of function
parameter types, supplying dummy arguments as necessary when calling the
function, e.g.,

template <class T>
void foo(T * ptr)
{
T t;
}

int main()
{
foo((A*)0);
foo((B*)0);

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top