问题
Why char* pstr="hello"; pushArg(pstr);
still invoke such template?
You see there is &&(!std::is_same<char, typename std::remove_cv_t<std::remove_pointer_t<T>>>::value)
already.
template <typename T,
typename std::enable_if<(!std::is_same<lua_CFunction, T*>::value)
&& std::is_pointer<T>::value
&& (!std::is_same<std::string*, T>::value)
&& (!std::is_same<char, typename std::remove_cv<std::remove_pointer<T>>>::value)
&& (!std::is_same<unsigned char, typename std::remove_cv<std::remove_pointer<T>>>::value)
int pushArg(T& val)
{
}
回答1:
First, you have tagged your answer with C++11
but you use std::remove_cv_t
from C++14.
In C++17, your function would look like this:
template <typename T,
std::enable_if_t<
std::is_pointer_v< T >
&& !std::is_same_v< std::string* , T >
&& !std::is_same_v< char , typename std::remove_cv_t<std::remove_pointer_t<T>> >
&& !std::is_same_v< unsigned char, typename std::remove_cv_t<std::remove_pointer_t<T>> >,
void
>* = nullptr
>
int pushArg(T& val) {
return 0;
}
and the error will be thrown in case of passing char *pstr = "hello"
.
And in C++11, you are missing typename std::remove_cv<typename std::remove_pointer<T>::type>::type
part. Full code below:
template <typename T,
typename std::enable_if<
std::is_pointer< T >::value
&& !std::is_same< std::string* , T >::value
&& !std::is_same< char , typename std::remove_cv<typename std::remove_pointer<T>::type>::type >::value
&& !std::is_same< unsigned char, typename std::remove_cv<typename std::remove_pointer<T>::type>::type >::value,
void
>::type* = nullptr
>
int pushArg(T& val) {
return 0;
}
DEMO
来源:https://stackoverflow.com/questions/65301158/stdenable-if-to-filter-out-the-argument-with-the-type-of-char