找出参数是constexpr [英] Find out the parameter is constexpr

查看:146
本文介绍了找出参数是constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何type_traits或方法都可以找出参数是否为constexpr?

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

示例

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可以应用于constexpr参数,
参数可以在运行。然而,
递归在运行时可能不够有效。

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

我们是否还要分开
运行时的实现和constexpr函数的编译时间?
如果我们不能这样做,我们可以强制用户
不能使用constexpr函数做一些运行时
评估?

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?

推荐答案

我认为这可能会得到你想要的

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 ;   
}

我使用了解SFINAE 作为参考。

问题的另一部分的答案是肯定的,因为它看起来一个 constexpr 函数模板并不总是可用于常量表达式。所以这导致这样的解决方案,这个有点麻烦的例子:

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) ;
} 

这篇关于找出参数是constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆