Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading function calls for compile-time constants

Tags:

c++

c++11

I'm interested to know whether one can distinguish between function calls using arguments provided by compile-time constants and those without?

For example:

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

Is there any way to provide overloads that distinguish between these two cases? Or more generally, how do I detect the use of a literal type?

I've looked into constexpr, but a function parameter cannot be constexpr. It would be neat to have the same calling syntax, but be able to generate different code based on the parameters being literal types or not.

like image 384
dgrine Avatar asked Oct 18 '25 12:10

dgrine


1 Answers

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
like image 170
Barry Avatar answered Oct 21 '25 01:10

Barry