简体   繁体   English

为什么 void_t 在 SFINAE 中不起作用但 enable_if 可以

[英]Why void_t doesnt work in SFINAE but enable_if does

I was trying to understand how SFINAE works and I was experimenting with this code我试图了解SFINAE工作原理,并且正在尝试使用此代码

#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>();
}

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_t s should be independent right?两个void_t应该是独立的吧? Since one line checks for x and the other for y .因为一行检查x ,另一行检查y How can I fix?我该如何解决?

This seems to be related to CWG issue #1980 (credits to TC for correcting me) .这似乎与CWG 问题 #1980 (感谢TC纠正我)有关

As a workaround you can define void_t as:作为一种解决方法,您可以将void_t定义为:

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

(from cppreference) (来自 cppreference)

live example on wandbox魔杖盒上的现场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM