Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use type-traits to make this array-to-pointer conversion unambiguous?

I would like to discern between static arrays and pointers.

The following example fails to compile due to array-to-pointer conversions having exact match, making both foo's possible candidates.

Am I able to get the 2nd overload of foo to be unambiguously selected using type traits?

#include <iostream>

template<typename T>
void foo(const T* str)
{
    std::cout << "ptr: " << str << std::endl;
}

template<typename T, size_t N>
void foo(const T (&str)[N])
{
    std::cout << "arr: " << str << std::endl;
}

int main()
{
    foo("hello world"); // I would like the array version to be selected
    return 0;
}
like image 432
Steve Lorimer Avatar asked Jul 22 '14 06:07

Steve Lorimer


1 Answers

You may use the following:

namespace detail
{
    template <typename T> struct foo;

    template <typename T>
    struct foo<T*>
    {
        void operator()(const T* str) {std::cout << "ptr: " << str << std::endl;}
    };

    template <typename T, std::size_t N>
    struct foo<T [N]>
    {
        void operator()(const T (&str)[N]) {std::cout << "arr: " << str << std::endl;}
    };
}

template<typename T>
void foo(const T& t)
{
    detail::template foo<T>()(t);
}

Live example

like image 140
Jarod42 Avatar answered Oct 13 '22 03:10

Jarod42