Specializing function template for reference types

不羁岁月 提交于 2019-11-29 09:26:55

The type of both the expression y and the expression z is int. A reference appearing in an expression won't keep reference type. Instead, the type of the expression will be the referenced type, with the expression being an lvalue.

So in both cases, T is deduced to int, and thus the explicit specialization is not used at all.

What's important to note (other than that you should really use overloading, as another guy said), is that you have a non-reference function parameter in your template. Before any deduction of T against the argument type is done, the argument type will be converted from arrays to a pointer to their first element (for functions, arguments will be converted to function pointers). So a function template with a non-reference function parameter doesn't allow for accurate deduction anyway.

A reference is just an alias, not a type. So when you call f(z), it matches the first version with T=int, which is a better option that T=int&. If you change T to T&, then both int and int& arguments will call the second version.

I know it is not answer but, IMHO you can try this, with a trait like approach in a struct:

template<typename T>
struct value_traits
{
    static void print(){std::cout << "General" << std::endl ;} 
};

template<>
struct value_traits<const long>
{
    static void print(){std::cout << "const long" << std::endl ;} 
};

template<>
struct value_traits<std::vector<unsigned char> >
{
    static void print(){std::cout << "std::vector<unsigned char>" << std::endl ; }
};

template<>
struct value_traits<const int>
{
       static void print(){std::cout << "const int" << std::endl ;} 
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!