Let there be some template function foo with an integer argument of the template:

 template <int N> void foo() { } 

Is it possible to write such a function / functional object void bar(...int n...) that will call the function foo<n> inside if the parameter n can be calculated at the compilation stage and there will be a compilation error if n not can be calculated.

As far as I understand, this behavior is unacceptable in modern standards (even including C ++ 17, despite the Class template argument deduction), but maybe there are concepts to future standards that allow such behavior?

Hack with #define not to offer, of course.

  • What is the purpose for such a hypothetical code? - Constructor
  • @Constructor First theoretical. And it grew out of the desire to have the most universal function pow(a, b) = b^a for types for which type b*b not equal to the original type b . You can write a function with the pow<a>(b) , but then it will impose restrictions on a as a compile-time constant even for types that don't need it ( int ). - dortmund
  • Why else write something? You can simply call foo and if the parameter N cannot be calculated at the compilation stage, then there will be an error ... - VTT
  • @VTT, you can look at the previous comment ... Syntax foo<n> always imposes a restriction on n as a compile time constant. And I want to be able to impose a restriction sometimes. - dortmund
  • @dortmund Maybe then the error in the question: "and there will be a compilation error if n cannot be calculated." - VTT

1 answer 1

For bar(...) it is impossible, since the type of the arguments is not "forwarded" through "var-arg". But using overload - you can, for example,

 template<typename T1> void bar(T1 a1) { foo(a1); // если foo обьявлена как template (как в вопросе) то так можно } template<typename T1,typename T2> void bar(T1 a1,T2 a2) { foo(a1); foo(a2); } // и так далее столько сколько нужно. 

Then if you make a mistake when specifying the type - a compilation error will be generated.