结构内部允许静态断言吗?

发布于 2024-11-19 17:12:49 字数 223 浏览 2 评论 0原文

我有几个模板设置结构,可以在这些结构中使用静态断言吗?

template<typename T, int N, (and so on...)>
struct Settings{
  static const int n = N;
  STATIC_ASSERT(n == 5);
  typedef typename T GAGA;
}

感谢您的回复!

I have several template settings struct, is it ok, to use static asserts in these structs?

template<typename T, int N, (and so on...)>
struct Settings{
  static const int n = N;
  STATIC_ASSERT(n == 5);
  typedef typename T GAGA;
}

Thanks for your responses!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乄_柒ぐ汐 2024-11-26 17:12:50

我不知道你的 STATIC_ASSERT 是什么,但如果你使用 c++11 风格的 static_assert 编写它,那么它工作得很好,并且看起来非常适合静态断言。 (好吧,也许不检查它是 5,而是检查模板参数是否适合实例化)

template<typename T, int N>
struct Settings {   
  static const int n = N;   
  static_assert(n == 5, "Error");   
  typedef typename T GAGA; 
};

I don't know what your STATIC_ASSERT is but if you write it using c++11 style static_assert then this works fine and seems like a perfectly good use for static assert. (Well, perhaps not checking it's 5 but checking template parameters are suitable for instantating)

template<typename T, int N>
struct Settings {   
  static const int n = N;   
  static_assert(n == 5, "Error");   
  typedef typename T GAGA; 
};
居里长安 2024-11-26 17:12:50

您必须查看 STATIC_ASSERT 宏定义才能了解到底发生了什么。可以在此处使用的 STATIC_ASSERT 的常见实现可能是:

#define STATIC_ASSERT( x ) \
   typedef char static_assert_failed[ (x) ? 1 : -1 ]

通常需要一些技巧才能使行号成为 typedef 的一部分,以便多个 STATIC_ASSERT 可以使用> 可以在相同的上下文中使用,但您可以看到这是允许的,因为它将扩展到结构定义中的有效代码:

template<typename T, int N, (and so on...)>
struct Settings{
  static const int n = N;
  typedef char static_assert_failed[ (n == 5) ? 1 : -1 ];
  typedef typename T GAGA;
}

You would have to look at the STATIC_ASSERT macro definition to see what is exactly going on. A common implementation of STATIC_ASSERT that can be used there could be:

#define STATIC_ASSERT( x ) \
   typedef char static_assert_failed[ (x) ? 1 : -1 ]

Usually there is a bit more trickery to get the line number to be part of the typedef so that more than one STATIC_ASSERT can be used in the same context, but you can see that this is allowed as it will expand to valid code in the struct definition:

template<typename T, int N, (and so on...)>
struct Settings{
  static const int n = N;
  typedef char static_assert_failed[ (n == 5) ? 1 : -1 ];
  typedef typename T GAGA;
}
丑疤怪 2024-11-26 17:12:50
template<typename T, int N>
struct Settings
{  
STATIC_ASSERT(N == 5);  
typedef typename T GAGA;
};

我没有看到使用 n 的正当理由。

template<typename T, int N>
struct Settings
{  
STATIC_ASSERT(N == 5);  
typedef typename T GAGA;
};

I dont see a valid reason to use n.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文