c++ - Why do templates not implicitly instantiate to const or reference types? -
consider following function template explicit specializations.
template<typename t> void f(t); template<> void f<int>(int i) { std::cout << "f() chose int\n"; ++i; } template<> void f<const int&>(const int&) { std::cout << "f() chose const int&\n"; }
the first specialization can implicitly instantiated. second cannot, even if first specialization absent. unlike rules function overloading function taking int
or const int&
works fine (g()
in linked examples).
example specialization int
available. works.
http://coliru.stacked-crooked.com/a/1680748749f36631
example specialization const int&
available. compiles fails link.
http://coliru.stacked-crooked.com/a/ab8b068d3f807837
why template type deduction work way , why chosen work way? alternative template type deduction behave function overloading.
my understanding overloaded functions, compiler knows available options templates compiler must first decide , see if can instantiated. if case, requiring compiler search qualified variations on types unreasonable demand?
consider case of no explicit specializations:
template <typename t> void f(t x) { t y = 42 + x; std::cout << y; } int main() { int n = 1337; f(n); }
template argument deduction never deduces reference type, because alternative always deduce reference type. if did, above call f(n)
call f<int&>
, make t y = 42 + x;
ill-formed.
picking specialization happens after deduction complete.
the first specialization can implicitly instantiated. second cannot, even if first specialization absent.
you can't make f<int>
absent, declared here:
template<typename t> void f(t);
Comments
Post a Comment