Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between array pointer to array reference

Tags:

c++

c++11

I want to write a function which distinguish between arrays and pointers. This is needed in order to figure size of literal strings. I tried:

template<typename Ty>
void f(const Ty* rhs) {
    std::cout << __FUNCTION__ << rhs << std::endl;
}

template<typename Ty, size_t Dm>
void f(const Ty(&rhs)[Dm]) {
    std::cout << __FUNCTION__ << rhs << std::endl;
}

int main(int, char*[]) {
    const char arr0[] = "test2";
    const char* ptr = "test3";
    const char arr6[6] = "test4";
    f("test1");
    f(arr0);
    f(ptr);
    f(arr6);
    return 0;
}

But the compiler (VS2013) tells me that the call is ambiguous. Any hints?

Thanks in advance.

like image 407
U. Mann Avatar asked Aug 24 '26 19:08

U. Mann


1 Answers

Unfortunately, the call are ambiguous.

As workaround, you may add an extra layer:

template<typename Ty>
void f_pointer(const Ty* rhs) {
    std::cout << __FUNCTION__ << rhs << std::endl;
}

template<typename Ty, size_t Dm>
void f_array(const Ty(&rhs)[Dm]) {
    std::cout << __FUNCTION__ << rhs << std::endl;
}

template<typename T>
std::enable_if_t<std::is_array<T>::value>
f(const T&t)
{
    f_array(t);
}

template<typename T>
std::enable_if_t<!std::is_array<T>::value>
f(const T&t)
{
    f_pointer(t);
}

Live Demo

like image 186
Jarod42 Avatar answered Aug 26 '26 11:08

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!