为什么void_t在SFINAE中不起作用,但enable_if可以 [英] Why void_t doesnt work in SFINAE but enable_if does

查看:58
本文介绍了为什么void_t在SFINAE中不起作用,但enable_if可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 SFINAE 的工作方式,并且正在尝试使用此代码

I was trying to understand how SFINAE works and I was experimenting with this code

#include <type_traits>

struct One { 
  using x = int; 
};
struct Two { 
  using y = int; 
};

template <typename T, std::void_t<typename T::x>* = nullptr>
void func() {}
template <typename T, std::void_t<typename T::y>* = nullptr>
void func() {}

/*template <typename T, std::enable_if_t<std::is_same_v<typename T::x, typename T::x>>* = nullptr>
void func() {}
template <typename T, std::enable_if_t<std::is_same_v<typename T::y, typename T::y>>* = nullptr>
void func() {} */



int main() {
  func<One>();
  func<Two>();
}

注释的代码有效,但第一个无效。编译器给我错误,指出重新定义并且模板参数推导失败。有人可以解释为什么会这样吗?两个 void_t 应该是独立的吧?由于其中一行检查 x ,另一行检查 y 。如何解决?

The commented code works but the first doesn't. The compiler gives me errors saying that there is a redefinition and that template argument deduction failed. Could someone explain why this happens? The two void_ts should be independent right? Since one line checks for x and the other for y. How can I fix?

推荐答案

这似乎与 CWG问题#1980 (向 TC 来纠正我)

This seems to be related to CWG issue #1980 (credits to T.C. for correcting me).

作为解决方法,您可以定义 void_t 为:

As a workaround you can define void_t as:

template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

(来自cppreference)

魔盒上的实时示例

这篇关于为什么void_t在SFINAE中不起作用,但enable_if可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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