如何使用type-traits使这个数组到指针的转换无歧义? [英] How can I use type-traits to make this array-to-pointer conversion unambiguous?
本文介绍了如何使用type-traits使这个数组到指针的转换无歧义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于数组到指针的转换具有完全匹配
/ strong>,使 foo
的可能候选人。 code> foo 以使用类型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); //我想选择数组版本
return 0;
}
解决方案
template< typename T>
typename std :: enable_if< std :: is_pointer< T> :: value,void> :: type
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;
}
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;
}
解决方案
template<typename T>
typename std::enable_if<std::is_pointer<T>::value,void>::type
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;
}
这篇关于如何使用type-traits使这个数组到指针的转换无歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文