Calling overloading functions for compile-time constants

I am wondering if it is possible to distinguish between function calls with arguments provided by compile-time constants and those that do not?

For example:

int a = 2;
foo( a )  // #1: Compute at run-time
foo( 3 )  // #2: Compute at compile-time

      

Is there a way to provide overloads that differentiate the two? Or, more generally, how do you determine the use of a literal?

I looked at constexpr but the function parameter cannot be constexpr. It would be neat to have the same calling syntax, but be able to generate different code based on parameters that are literal types or not.

+3


source to share


3 answers


I think the above answers somehow misunderstood what this question was trying to do.

Is there a way to provide overloads that differentiate the two? Or, more generally, how do you determine the use of a literal?

that's what an rvalue reference is for. Literal type is r value.

It would be neat to have the same calling syntax, but be able to generate different code based on parameters that are literal types.



you can simply overload your foo () function like:

void foo(int&& a);

      

So when you call a function with a literal like foo (3), the compiler knows you need the above overload, since 3 is an rvalue. If you call the function like foo (a), the compiler will pick up your original version foo(const int& a);

as it int a=2;

is an lvalue.

And it gives you the same calling syntax.

+2


source


You cannot distinguish between a compile-time literal int

and a run-time variable int

. If you need to do this, you can provide an overload that can only work at compile time:



void foo(int ); // run-time

template <int I>
void foo(std::integral_constant<int, I> ); // compile-time

      

+8


source


In general, you could not get the evaluation of foo (3) at compile time. What if foo (x) was defined to add x days to the current date - and you first run the program next Tuesday? If it really is a constant, then use a symbolic constant. If it's a simple function, you can try a definition (which will be replaced at compile time by the implementation, but it will be evaluated at runtime)

eg.

#define MIN(x,y) ((x)<(y)?(x):(y))

      

-2


source







All Articles