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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With