std::enable_if to filter out the argument with the type of char*

一笑奈何 提交于 2021-01-07 01:27:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!