考虑一下:
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/