Find out the parameter is constexpr

前端 未结 3 1862
走了就别回头了
走了就别回头了 2021-01-23 04:54

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          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 05:28

    I think this may get you what you want

    #include 
    
    template 
    class is_constexpr
    {
       typedef char true_type ;
       struct false_type { true_type _[2] ; } ;
    
       template 
       static true_type has_constexpr( U & ) ;
    
       template 
       static false_type has_constexpr(...) ;
    
       public:
          enum { value = ( sizeof(has_constexpr(0)) == sizeof(true_type)) } ;
    } ;
    
    int main()
    {
       constexpr int i = 10 ;
       int k = 20 ;
    
       std::cout << is_constexpr::value << std::endl ;
       std::cout << is_constexpr::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 
    T f2( T num )
    { 
       return num + 1;
    }
    
    template 
    constexpr T f1( T num )
    {
       return num ;
    }
    
    template 
    constexpr T f(T num)
    {
       return  is_constexpr::value ? f1(num) : f2(num) ;
    } 
    

提交回复
热议问题