Alexander Bily
Alexander Bily

Reputation: 975

C++ SFINAE void_t not working

I tried running following code, which should rely on void_t trick, where more specialized class template should be chosen (in this case second one)

#include <iostream>
#include <type_traits>

template <class ...>
using void_t = void;

template <class T, class = void>
struct is_incrementable : public std::false_type { };
template <class T>
struct is_incrementable<T, void_t<decltype(++(std::declval<T>()))>> : public std::true_type { };

int main()
{
    std::cout << std::boolalpha;
    std::cout << is_incrementable<int>::value << std::endl;
    return 0;
}

I am using MSVC 2015. However, the result of is_incrementable<int>::value is false. Is there anything wrong with my code or is there problem with my compiler?

Upvotes: 0

Views: 190

Answers (1)

Brian Bi
Brian Bi

Reputation: 119382

std::declval<T> has return type T&&, so std::declval<int>() is an rvalue of type int. The result of "false" is telling you that an int rvalue is not incrementable, which is correct.

You can replace std::declval<T> with std::declval<T&> to get the program to tell you whether an lvalue of type T is incrementable. If you make this change to your program, it should print "true".

Upvotes: 2

Related Questions