c++14 SFINAE dereference iterator
Original problem: write function f (r), if R is an iterator, then return F (*r), otherwise return R.
summary: questions:
in subsequent implementations, the requirements for iterators are relaxed: R with Lvalue R, or if *r is legal, then there is an iterator type. Meaning That:
write the function F (r), if the Lvalue R can be dereferenced, return F (*r), otherwise return R.
problem Analysis:
The return value type of f changes with the actual parameter. If R is an int * * type, A minimum of two F overloads of int *f (int * *) and int f (int *) are required. These function overloads need to be generated by a call to f at compile time through generics .
when called, the overload resolution stage requires the compiler to select the appropriate function Template.
-
t The lvalue can be dereferenced, Select the function template ( 1
template <class t>auto f (T r) {
Span style= "color: #0000ff" >return f (*r);}
- Otherwise select a function template ( 2)
template <class t>auto f (T r) {
return
question:
questions:
implementation:
1#include <cassert>2 3#include <type_traits>4#include <utility>5 6Template <classT>7 Auto F (T x, ...) {8 returnx;9 }Ten oneTemplate <classTclass= Decltype (*std::d eclval<t> ()) > aAuto F (T x,int) { - returnF (*x, 0); - } the - intmain () { - intx =3, *p = &x; -Assert (f (&p,0)==3); + - return 0; +}
text:
Withheld
FAQ:
Not Yet.
references:
Http://en.cppreference.com/w/cpp/concept/Iterator
Http://en.cppreference.com/w/cpp/language/overload_resolution (return Type Deduction)
Http://en.cppreference.com/w/cpp/utility/declval
Http://en.cppreference.com/w/cpp/language/overload_resolution
Http://en.cppreference.com/w/cpp/language/template_argument_deduction
c++14 SFINAE dereference iterator