Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a func. is a constexpr? and mark other func. constexpr depending on it?

Tags:

Assuming i have some function template f1:

template<typename f2>
int f1(int i, int j) noexcept {
  return i + j + f2(i, j);
}

is there way to determine if f2(i, j) can be a constexpr. (no matter it is a func. or a functor) and so mark f1<f2> as a constexpr too?

I am thinking of using SFINAE here some how, but didn't find how to detect constexpr using type traits

like image 771
Amabo Carab Avatar asked Jun 23 '16 12:06

Amabo Carab


People also ask

How do I know if a function is constexpr?

The easiest way to check whether a function (e.g., foo ) is constexpr is to assign its return value to a constexpr as below: constexpr auto i = foo(); if the returned value is not constexpr compilation will fail.

Can constexpr functions call non constexpr functions?

A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.

Is constexpr evaluated at compile time?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

Is constexpr guaranteed?

Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.


1 Answers

You can mark f1 as constexpr.

template<typename f2>
constexpr int f1(int i, int j) noexcept {
  return i + j + f2(i, j);
}

The template function f1 would be constexpr iif f2 is.

if f2 is not, you will get error only when you use f1 in a constant compile time expression.

Demo

like image 186
Jarod42 Avatar answered Oct 06 '22 23:10

Jarod42