Function call selection using ternary operator

M

marco_segurini

Hi,

I am wondering if there is a way to use the ternary operator to select
a function, between two, even if at least one of them is overloaded.
Ex:

void f1(int) {}
void f1(double) {}
void f2(int) {}
//void f2(double) {}

int main()
{
bool bTest = false;
(bTest ? f1 : f2)(int(1)); // this statement does not compile
return 0;
}

TIA.
Marco
 
S

Sumit Rajan

marco_segurini said:
Hi,

I am wondering if there is a way to use the ternary operator to select
a function, between two, even if at least one of them is overloaded.
Ex:

void f1(int) {}
void f1(double) {}
void f2(int) {}
//void f2(double) {}

int main()
{
bool bTest = false;
(bTest ? f1 : f2)(int(1)); // this statement does not compile

bTest ? f1(int(1)) : f2(int(1));

Regards,
Sumit.
 
M

marco_segurini

Sumit Rajan said:
bTest ? f1(int(1)) : f2(int(1));

Thanks for your reply Sumit.

This solution is the same as use:

if (bTest)
f1(1);
else
f2(1);

My goal is to avoid to repeat the actual parameters list (1).

Bye.
Marco.
 
R

Richard Herring

In message said:
Thanks for your reply Sumit.

This solution is the same as use:

if (bTest)
f1(1);
else
f2(1);

My goal is to avoid to repeat the actual parameters list (1).

You need a typedef to disambiguate the pointer to the overloaded
function:.

typedef void (*FInt)(int);
typedef void (*FDouble)(double); // etc

(bTest ? FInt(f1) : FInt(f2)) (1);
 
D

Dan Cernat

Hi,

I am wondering if there is a way to use the ternary operator to select
a function, between two, even if at least one of them is overloaded.
Ex:

void f1(int) {}
void f1(double) {}
void f2(int) {}
//void f2(double) {}

int main()
{
bool bTest = false;
(bTest ? f1 : f2)(int(1)); // this statement does not compile
return 0;
}

TIA.
Marco


use function pointers:

void f1(int x)
{
}

void f2(int x)
{
}

int main()
{
bool bTest = true;

void (*f)(int x);

f = bTest ? f1 : f2;
f(3);

return 0;
}

Dan
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top