Is this a bug in Visual C ++ 2010 or the correct behavior?
template<class T> T f(T const &r) { return r; } template<class T> T f(T &&r) { static_assert(false, "no way");
I thought that the function f (T & &) should never be called, but it is called with T = int &. Output:
main.cpp (10): error C2338: no way
main.cpp (17): see reference to function template instantiation 'T f (T)' being compiled
with
[
T = int &
]
Update 1 Do you know any C ++ x0 compiler as a reference? I tried a trial online test but could not compile the r-value link.
Update 2 Workaround (using SFINAE):
#include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_reference.hpp> template<class T> T f(T &r) { return r; } template<class T> typename ::boost::disable_if< ::boost::is_reference<T>, T>::type f(T &&r) { static_assert(false, "no way"); return r; } int main() { int y = 4; f(y); // f(5); // generates "no way" error, as expected. }
Update 3 Some of the compilers run on static_assert (false, "no way"), even if the function template is not instantiated. Workaround (thanks to @Johannes Schaub - litb)
template<class T> struct false_ { static bool const value = false; }; ... static_assert(false_<T>::value, "no way");
or
static_assert(sizeof(T) == sizeof(T), "no way");
source share