user2037593
user2037593

Reputation:

Deduce exact type of function template parameter

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?

Upvotes: 0

Views: 486

Answers (1)

David G
David G

Reputation: 96790

You'd have to pass the decltype of the argument. Use this macro to get over the syntactical hurdles:

namespace detail{
    template <typename T> void test(T){std::cout << "T" << std::endl;}
    template <> void test<>(int){std::cout << "int" << std::endl;}
    template <> void test<>(int&){std::cout << "int&" << std::endl;}
}

#define TEST(x) detail::test<decltype(x)>(x)

Now simply call with the arguments:

TEST(x) // int
TEST(y) // int&

Upvotes: 3

Related Questions