void_t fails on Visual Studio 2015

2019-03-18 02:50发布

I don't understand why the following test always fails with Visual Studio 2015 (the static_assert triggers):

#include <type_traits>
using namespace std;

template<class T> using try_assign = decltype(declval<T&>() = declval<T const&>());
template<class, class = void> struct my_is_copy_assignable : false_type {};
template<class T> struct my_is_copy_assignable<T, void_t<try_assign<T>>> : true_type {};

int main()
{
    static_assert(my_is_copy_assignable<int>::value, "fail");
    return 0;
}

It's basically the transcription of Walter E Brown's example usage of void_t from his cppcon 2014 presentation "Modern Template Metaprogramming - A compendium".

It's important to note that this alternate version works so I don't think that the problem lies in MSVC's incomplete support to expression SFINAE.

template<class T>
using try_assign = decltype(declval<T&>() = declval<T const&>());

template<class T>
struct my_is_copy_assignable
{
  template<class Q, class = try_assign<Q>>
  static true_type tester(Q&&);
  static false_type tester(...);
  using type = decltype(tester(declval<T>()));
};

I know about std::is_copy_assignable but I'm just interested in better understanding the various metaprogramming techniques available in the different revisions of C++. I read several threads about void_t on the web but I still don't understand why this example fails.

The interesting thing is that with GCC 4.8.2 it works fine (using the CWG 1558 workaround, which is the same that the Microsoft's version does).

Is it a known Visual Studio bug, or am I doing something wrong?

2条回答
劳资没心,怎么记你
2楼-- · 2019-03-18 03:03

Walter E. Brown at CppCon 2014 also mentioned the following factorization which allows to replace try_assign with arbitrary condition.

#include <type_traits>
#include <utility>

template<class T>
using try_assign = decltype(std::declval<T&>() = std::declval <T const &>());

template<class T, template<class> class Op, class = void>
struct is_valid : std::false_type { };

template<class T, template<class> class Op>
struct is_valid<T, Op, std::void_t<Op<T>>> : std::true_type { };

template<class T>
using is_copy_assignable = is_valid<T, try_assign>;

int main()
{
    static_assert(is_copy_assignable<int>::value, "fail");
    return 0;
}

This factorization compiles OK with VS 2015. Now remove is_copy_assignable and substitute into is_valid. You end up with the code you presented and which doesn't compile (VS 2015).

This suggests there's a bug in VS 2015 and it's not related to CWG 1558. In CWG issue the standard was unclear whether unused arguments in alias template specializations could result in substitution failure or are simply ignored.

查看更多
Rolldiameter
3楼-- · 2019-03-18 03:07

This does look like a SFINAE issue in VC++. Using a dependent decltype in the template argument of partial specialization of a class template isn't yet supported. It should work in VS 2015 Update 1.

查看更多
登录 后发表回答