Why void_t doesnt work in SFINAE but enable_if does

徘徊边缘 提交于 2020-01-21 02:38:45

问题


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

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?


回答1:


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

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;

(from cppreference)

live example on wandbox



来源:https://stackoverflow.com/questions/44845945/why-void-t-doesnt-work-in-sfinae-but-enable-if-does

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!