0

I would like to know if a templated type has a 'push_back' method. I tried this example : Is it possible to write a template to check for a function's existence?

my code :

template <typename T>
class has_push_back
{
    typedef char one;
    typedef long two;

    template <typename C> static one test(char[sizeof(&C::push_back)]);
    template <typename C> static two test(...);

public:
    enum { value = (sizeof(test<T>(0)) == sizeof(char)) };
};

My call :

    template <typename T>
    HTTPMessage Serializer::GetHTTPMessage(T varToSerialize)
    {
       std::cout << has_push_back<T>::value << std::endl;
       //some code
    }

Unfortunatly I got this error when GetHTTPMessage is called with std::string :

'overloaded-function': illegal sizeof operand

note: see reference to class template instantiation 'has_push_back' being compiled with [ T=std::string ]

I don't understand why it does not compile.

Community
  • 1
  • 1
Morgan
  • 476
  • 9
  • 23

1 Answers1

-1

SFINAE is not yet properly supported in VS2015

Though it seem to be possible (notice that I only check for presence of specific overload):

#include <type_traits>

template< typename T, typename = void > struct
has_push_back
{
    static bool const value = false;
};

template< typename T > struct
has_push_back
<
    T
,   typename ::std::enable_if_t
    <
        ::std::is_same
        <
            void
        ,   decltype(::std::declval< T >().push_back(::std::declval< typename T::value_type >()))
        >::value
    >
>
{
    static bool const value = true;
};

::std::cout << has_push_back< int >::value << ::std::endl; // 0
::std::cout << has_push_back< ::std::vector< int > >::value << ::std::endl; // 1
user7860670
  • 35,849
  • 4
  • 58
  • 84