Is it possible to make a function behave differently for a constant argument or a variable argument?

For example factorial (n), if the argument is a constant (expression) then the result is deterministic and can be executed at compile time (using template metaprograms).

Is it possible to just write one function so that whenever it is called, if the argument is a constant then the result will be computed at compile time, if it is a variable then it will do the computation at startup time?

+3


source to share


1 answer


This is what functions are for constexpr

. Functions constexpr

were introduced in C ++ 11. When called with constant expressions that can be evaluated at compile time, they are usually evaluated at compile time (and sometimes you can force this to happen). However, it is usually not possible to provide a guarantee. Otherwise, they are evaluated at runtime (and you can call them just like regular functions with constant or non-constant arguments, evaluated at runtime).

Aside from not guaranteeing their compile-time estimate, the function constexpr

has limitations: it must consist of only one single return statement , so if you're looking for a way to perform computations of any complexity, this won't suit your needs. However, the features constexpr

are probably the closest thing to what you are looking for.



Since you mention an example function factorial()

, this is how it looks with a function constexpr

:

#include <iostream>

using namespace std;

constexpr int factorial(int n)
{
    return (n == 0) ? 1 : factorial(n - 1);
}

int foo() 
{ 
    int result = 1;
    // do some processing...
    return result; 
}

int main()
{
    int v[factorial(5)]; // Evaluated at compile-time
    cout << factorial(foo()); // Evaluated at run-time
}

      

+5


source







All Articles