c++ - 静态断言和 SFINAE

标签 c++ c++11 sfinae static-assert

考虑一下:

template <typename T>
struct hash
{
     static_assert(false,"Not implemented.");
};

struct unhashable {};

template <typename T>
auto test(const T &t) -> decltype((*(hash<T> const *)nullptr)(t),int);

void test(...);

int main()
{
    std::cout << std::is_same<decltype(test(std::declval<unhashable>())),void>::value;
}

除了明显缺少 header 之外,这应该编译吗?

换句话说,我问的是在推导重载函数模板的返回值时是否要求在尾随 decltype 内触发静态断言失败以停止编译,或者是否只需丢弃重载。

在 gcc 4.7 上,编译失败。我非常肯定这将在 gcc 4.8 中编译正常(但目前无法检查)。谁是对的?

最佳答案

编译必须在任何兼容的编译器中失败。

SFINAE 规则基于声明而非定义。 (抱歉,如果我在这里使用了错误的术语。)我的意思是:

对于类/结构:

template < /* substitution failures here are not errors */ >
struct my_struct {
    // Substitution failures here are errors.
};

对于函数:

template </* substitution failures here are not errors */>
/* substitution failures here are not errors */
my_function( /* substitution failures here are not errors */) {
    /* substitution failures here are errors */
}

此外,给定模板参数集的结构/函数不存在也受 SFINAE 规则的约束。

现在 static_assert 只能出现在替换失败是错误的区域,因此,如果它触发,您将得到编译器错误。

例如,以下是 enable_if 的错误实现:

// Primary template (OK)
template <bool, typename T>
struct enable_if;

// Specialization for true (also OK)
template <typename T>
struct enable_if<true, T> {
    using type = T;
};

// Specialization for false (Wrong!)
template <typename T>
struct enable_if<false, T> {
    static_assert(std::is_same<T, T*>::value, "No SFINAE here");
    // The condition is always false.
    // Notice also that the condition depends on T but it doesn't make any difference.
};

然后试试这个

template <typename T>
typename enable_if<std::is_integral<T>::value, int>::type
test(const T &t);

void test(...);

int main()
{
    std::cout << std::is_same<decltype(test(0)), int>::value << std::endl; // OK
    std::cout << std::is_same<decltype(test(0.0)), void>::value << std::endl; // Error: No SFINAE Here
}

如果你为 false 移除 enable_if 的特化,那么代码编译并输出

1
1

关于c++ - 静态断言和 SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16302977/

相关文章:

深度复制链表的 C++ 构造函数

c++ - 如何配置 Eclipse 以使用特定的 MinGW 工具链

c++ - 如果原始源代码行无法编译,是否可以让模板选择备用源代码行?

C++ std::stringstream 操作优化

C++ 模板和 header 分配

c++ - 如何不使用单例?

c++ - 如何在 sleep 时唤醒 std::thread

c++ - auto 和 decltype 的关系

c++ - 让 SFINAE 在重载函数对象上使用 `is_callable`

c++ - 排除使用显式构造的 std::pair 构造函数