函数,只需要文字整数 [英] function that takes only literal integers

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

问题描述

我正在寻找一种方法来模拟C ++中的某些重载的GCC内置函数。内置函数类似于:

  __ builtin_foo(char * a,signed int b); 
__builtin_foo(short * a,signed int b);
__builtin_foo(long * a,signed int b);

在GCC中硬编码的特殊限制: b 必须是字面值,即可以调用:

  __ builtin_foo((char *)0,1); 

但不能:

  extern int val; 
__builtin_foo((char *)0,val);

会产生编译器错误。我已经用 std :: enable_if 来模拟这个,但是找不到一种方法来强制只接受字面量参数。有没有办法做到这一点?

解决方案

你可以使用宏和GCC内在模拟它__builtin_constant_p

  constexpr int foo(int i){return i; } 

#define FOO(i)do {\
static_assert(__ builtin_constant_p(i),Not an constant); \
foo(i); \
} while(false)

这将允许 FOO (1)来编译,但不是 int i = 1;然而, __ builtin_constant_p 的结果取决于优化(FOO(i); c



<级别,在较高优化级别 const 变量被视为常量,因此它不仅接受文字。



当然,如果你愿意允许常量表达式,而不只是文字,那么你所要做的就是在需要常量表达式的上下文中使用变量,例如静态断言或非类型模板参数。


I'm looking for a way to simulate certain overloaded GCC built-ins in C++. The built-ins are similar to these:

__builtin_foo(char *a, signed int b);
__builtin_foo(short *a, signed int b);
__builtin_foo(long *a, signed int b);

With a special limitation hard coded in GCC: b must be a literal value, i.e. you can call:

__builtin_foo((char *)0, 1);

but not:

extern int val;
__builtin_foo((char *)0, val);

which generates a compiler error. I've fiddled with std::enable_if to simulate this but cannot find a way to enforce that only literal arguments are accepted. Is there a way to do this?

解决方案

You can sort of simulate it using a macro and the GCC intrinsic __builtin_constant_p

constexpr int foo(int i) { return i; }

#define FOO(i) do { \
  static_assert(__builtin_constant_p(i), "Not a constant"); \
  foo(i); \
} while (false)

This will allow FOO(1) to compile, but not int i = 1; FOO(i);

However, the result of __builtin_constant_p depends on the optimisation level, at higher levels of optimisation const variables are treated as constants, so it doesn't only accept literals.

Of course if you're willing to allow constant-expressions, not just literals, then all you have to do is use the variable in a context that requires a constant-expression, such as a static assertion or a non-type template argument.

这篇关于函数,只需要文字整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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