ar2015 ar2015 - 1 year ago 92
C++ Question

Force compiler to accept only compile time argument (floating point)

Can I force compiler to accept only a

or a non-variable input to a function?

I am looking for allowing only compile time values to a function. Either using template or any other method.

Here, there is a working example for
templates. The problem with
s is that they cannot be used as template arguments.

#include <iostream>

template <double x>
void show_x()
std::cout<<"x is always "<<x<<" in the entire program."<<std::endl;

int main()
return 0;

error: ‘double’ is not a valid type for a template non-type parameter


To those who have marked this question as a duplicate, I have to say:

I ask question

How to solve problem A?


Solution B does not work for problem A, I need another solution

Then you linked me to why solution
does not work.

That is totally illogical.

Answer Source

I'm not sure exactly what you want, but here is a way to reject non-constant expressions in a function call. Unfortunately it uses a macro which is bad because of name pollution, but maybe if you give your function a strange name then it won't hurt too much:

void f(double d) {}
#define f(x) do { constexpr decltype(x) var = x; f(var); } while (0)

int main() 
    f(1.0);      // OK
    f(1 + 2);    // OK, constant expression with implicit conversion
    double e = 5.0;
    f(e);        // compilation error, `e` is not a constant expression

If you want to reject constant expressions which aren't exactly double type already, that would be possible too (not sure from your question whether that is a requirement).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download