Пришлось сделать похожий код:
#include <type_traits>
template<typename S>
struct probe {
template<typename T, typename U = S, std::enable_if_t<
std::is_same<T&, U>::value &&
!std::is_const<T>::value, int> = 0>
operator T& () const;
template<typename T, typename U = S&&, std::enable_if_t<
std::is_same<T&&, U>::value &&
!std::is_const<T>::value, int> = 0>
operator T&& ();
template<typename T, typename U = S, std::enable_if_t<
std::is_same<T const&, U>::value, int> = 0>
operator T const& () const;
template<typename T, typename U = S&&, std::enable_if_t<
std::is_same<T const&&, U>::value, int> = 0>
operator T const&& () const;
};
struct some_type {};
struct other_type {};
auto test_call(some_type const&, other_type) -> std::false_type;
auto test_call(some_type&, other_type) -> std::true_type;
int main() {
static_assert(decltype(test_call(probe<some_type&>{}, other_type{}))::value, "");
}
Он работает под GCC и Clang, но не компилируется в Visual Studio с неоднозначной ошибкой разрешения. Какой компилятор не так и почему?
GCC и Clang, Визуальная студия
Вот результат msvc:
source_file.cpp(31): error C2668: 'test_call': ambiguous call to overloaded function source_file.cpp(28): note: could be 'std::true_type test_call(some_type &,other_type)' source_file.cpp(27): note: or 'std::false_type test_call(const some_type &,other_type)' source_file.cpp(31): note: while trying to match the argument list '(probe<some_type &>, other_type)' source_file.cpp(31): error C2651: 'unknown-type': left of '::' must be a class, struct or union source_file.cpp(31): error C2062: type 'unknown-type' unexpected
@ 1201ProgramAlarm, эти подробности предоставлены ссылками на живые демонстрации.
@ 1201ProgramAlarm Редактировал вопрос. Также полный вывод компилятора доступен в живом примере, на который я ссылался в вопросе. Скажите, есть ли еще что-нибудь, что мне следует отредактировать.
@ r3musn0x Подробная информация об ошибках и т. д. должна быть включена в вопрос, а не при переходе по какой-либо внешней ссылке, поскольку эти ссылки могут измениться или испортиться.
Это может иметь какое-то отношение к расширению компилятора для VS, которое позволяет временному привязывать как к const ref, так и к обычному ref.
@AndyG может быть. Но мой тип должен быть только конвертируемым в some_type&, что не временно. Я предполагаю, что это ошибка MSVC, но я хотел подтвердить свою гипотезу, прежде чем сообщать.





Код можно сократить до следующие:
#include <type_traits>
struct some_type {};
struct probe {
template<typename T, std::enable_if_t<!std::is_const<T>::value, int> = 0>
operator T& () const;
};
auto test_call(some_type const&) -> std::false_type;
auto test_call(some_type&) -> std::true_type;
int main() {
static_assert(decltype(test_call(probe{}))::value, "");
}
Согласно [temp.deduct.conv] / 5 & 6:
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A. However, there are four cases that allow a difference:
If the original A is a reference type, A can be more cv-qualified than the deduced A (i.e., the type referred to by the reference)
...
These alternatives are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails.
T выводится как some_type для обоих вызовов функций. Затем согласно [over.ics.rank] / 3.3:
User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2.
probe -> some_type& -> some_type& лучше, чем probe -> some_type& -> const some_type&, поэтому здесь нет двусмысленности, GCC и Clang правы.
Кстати, если мы удалим часть std::enable_if_t<...> в приведенном выше коде, MSVC и GCC завершатся ошибкой во время компиляции Clang. Для дальнейшего анализа остановимся на первом test_all:
#include <type_traits>
struct some_type {};
struct probe {
template<typename T>
operator T& () const
{
static_assert(std::is_const_v<T>);
static T t;
return t;
}
};
auto test_call(some_type const&) -> std::false_type;
int main() {
test_call(probe{});
}
Затем мы обнаруживаем, что static_assert запускает только под Clang. Другими словами, Clang выводит T как some_type вместо const some_type. Думаю, это ошибка Clang.
«Это работает ... но не в Visual Studio». Как так? Не компилируется? Показывает неправильный вывод при запуске? Пожалуйста, добавьте эти данные к вашему вопросу.