StereoMatching StereoMatching - 1 month ago 20
C++ Question

Find out the parameter is constexpr

Any type_traits or method could find out the parameters is a constexpr or not?

Example

size_t fibo_runtime(size_t num)
{
//implementation
}

constexpr size_t fibo(size_t num)
{
return is_constexpr<size_t>::value ? //this type traits looks weird and unreasonable
(num > 1 ? fibo(num - 1) * num : 1) :
fibo_runtime(num);
}


constexpr could apply on constexpr parameter and
the parameter be determined at run time. However,
recursive may not efficient enough on runtime.

Do we have anyway to separate the implementation of
runtime and compile time of constexpr functions?
if we could not do that, could we enforce the users
could not use the constexpr function to do some runtime
evaluation?

Answer

I think this may get you what you want

#include <iostream>

template <typename T>
class is_constexpr
{
   typedef char true_type ;
   struct false_type { true_type _[2] ; } ;

   template <typename U>
   static true_type has_constexpr( U & ) ;

   template <typename U>
   static false_type has_constexpr(...) ;

   public:
      enum { value = ( sizeof(has_constexpr<T>(0)) == sizeof(true_type)) } ;
} ;

int main()
{
   constexpr int i = 10 ;
   int k = 20 ;

   std::cout << is_constexpr<decltype(i)>::value << std::endl ;
   std::cout << is_constexpr<decltype(k)>::value << std::endl ;   
}

I used Understanding SFINAE as a reference.

Doing some more research I think I the answer to the other part of the question is yes, since it looks a constexpr function template is not always usable in a constant expression. So this leads to a solution like so, with this somewhat contrived example:

template <typename T>
T f2( T num )
{ 
   return num + 1;
}

template <typename T>
constexpr T f1( T num )
{
   return num ;
}

template <typename T>
constexpr T f(T num)
{
   return  is_constexpr<T>::value ? f1(num) : f2(num) ;
} 
Comments