我正在尝试了解SFINAE(我正在关注本教程),但有一些......“设计选择”我不明白,因此,我发现它们令人困惑。
假设我有这样的情况(包括重新实现std::enable_ifis there 只是为了展示我的理解enable_if)
// A default class (class type) declaration. Nothing unusual.
template <bool, typename T = void>
struct enable_if
{};
// A specialisation for <true, T> case. I understand 'why-s' of this.
// -- 'why-s': if I attempt to access 'enable_if<false, T>::type' (which does not exist) I will get a substitution failure and compiler will just "move-on" trying to match "other cases".
template <typename T>
struct enable_if<true, T> {
typedef T type;
};
// Here lies my problem:
template <class T,
typename std::enable_if<std::is_integral<T>::value,T>::type* = nullptr>
void do_stuff(T& t) { /* do stuff */ };
(1)我有一个“问题”的第一件事是bool文字 ( true/ false)。我知道它们是正确的,模板可以接受原始数据类型(普通旧数据类型)的编译时常量值,但如果我的任务是设计enable_if“机制”而不是使用true/false我会创建一个标记类true_t(或True)和false_t(或False)如下:
class true_t {}; // or True
class false_t {}; // or False
template<typename T>
class is_integral // just to have "something" to use with "enable_if"
{
using result = false_t;
};
template<>
class is_integral<int32_t> // same with all other int types
{
using result = true_t;
};
template <typename B, typename T = void>
struct enable_if
{};
template <typename T>
struct enable_if<true_t, T>
{
using type = T;
};
(2)我觉得多余的第二件事是需要指定typename T模板参数。enable_if如下实现会不会更容易/更好:
template <typename B>
struct enable_if
{};
template <>
struct enable_if<true_t>
{
using type = void; // the 'type' exists therefore substitution failure will not occur.
};
我很清楚我所有的提议都比目前现有的解决方案差很多,但我不明白为什么......SFINAE我剃掉了当前的功能(重要功能)的哪一部分?(甚至没有意识到……)
我知道,在这个网站上,我有义务以......单一的“类似问题的”格式提出一个问题,但如果你认为它可以接受,我还可以问一下这种语法是什么:
std::enable_if</* ... */>::type* = nullptr
完成?现在已经超出了我的理解范围...