In the following code uses the type inference rules for template parameters (this question is about C++14):
#include <iostream>
template <typename T>
void test(T x)
{
std::cout << "T x" << std::endl;
}
template <>
void test<int>(int x)
{
std::cout << "int x" << std::endl;
}
template <>
void test<int &>(int &x)
{
std::cout << "int &x" << std::endl;
}
int main()
{
int x = 5;
int &y = x;
test(x);
test(y);
return 0;
}
The rules clearly state that references are discarded (es explained, for example, here), so the output
int x
int x
is very much expected as the best matching overload. However in some cases, an output of
int x
int &x
may be desirable. Is there a way for template argument type deduction to infer what is, intuitively, the exact type of the parameter?
Aucun commentaire:
Enregistrer un commentaire