何时使用`static_assert`而不是SFINAE? [英] When to use `static_assert` instead of SFINAE?

查看:182
本文介绍了何时使用`static_assert`而不是SFINAE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用(并看到使用) static_assert 来标记不需要的模板参数值。但是,对于所有情况下,我发现它似乎更好,更优雅通过SFINAE禁用这些不需要的值。例如

 模板< typename T,
class = std :: enable_if< std :: is_floating_point< T> ;: :value> :: type>
struct Foo {...};

而不是

  template< typename T> 
struct Foo {
static_assert(std :: is_floating_point< T> :: value,
Foo< T> ;: T必须是浮点数:-();
。所以我的问题:何时使用;
};



<



p>我认为到目前为止我所学到的是以下



1 SFINAE是一个多功能和强大但可能非常复杂的工具,



2 SFINAE可用于多个任务,包括函数重载解析(其中一些似乎被视为其唯一目的)。一种相对简单的方法,除非它出现在(类或函数)的声明中,而不是其定义,所以 static_assert (或者可以在例如类转发声明中插入 static_assert ),这使得更多的逐字,因此更清晰的代码。但是,因为SFINAE是复杂的,它往往比一个简单的 static_assert 更难得到。



3 另一方面, static_assert 有一个更清晰的编译器错误消息的好处,有人似乎认为这是一个主要目的。

解决方案

我认为 static_assert 是正确的选择,如果你想强制执行 T 是一种浮点类型。此方法比SFINAE解决方案更清楚地说明您的意图。


I have been using (and seen used) static_assert to flag undesired values of template parameter values. However, for all cases I came across it seems better and more elegant to disable those undesired values via SFINAE. For example

template<typename T,
         class = std::enable_if<std::is_floating_point<T>::value>::type>
struct Foo { ... };

instead of

template<typename T>
struct Foo {
  static_assert(std::is_floating_point<T>::value,
                "Foo<T>: T must be floating point :-(");
  ...
};

So my question: when to use static_assert instead of SFINAE and why?

EDIT

I think what I've learned so far is the following

1 SFINAE is a versatile and powerful but potentially very complicated tool that can be used for many tasks, including function overload resolution (which some seem to regard as its only purpose).

2 SFINAE can be used in a relatively simple way where ever static_assert can, except that it appears in the declaration (of a class or function) rather than its definition (or is is possible to insert a static_assert into, say, a class forward declaration?). That makes more verbatim and hence clearer code. However, because SFINAE is complicated, it tends to be harder to get right than a simple static_assert.

3 On the other hand static_assert has the benefit of a clearer compiler error message, which some seem to regard as the main purpose of either.

解决方案

I think static_assert is the right choice if you want to enforce that T is a floating point type. This method states your intent more clearly than the SFINAE solution.

这篇关于何时使用`static_assert`而不是SFINAE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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