【问题标题】:Check method existence on a template with SFINAE on VS2015在 VS2015 上使用 SFINAE 检查模板上的方法是否存在
【发布时间】:2017-04-19 10:32:21
【问题描述】:

我想知道模板类型是否有“push_back”方法。 我试过这个例子:Is it possible to write a template to check for a function's existence?

我的代码:

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)) };
};

我的电话:

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

不幸的是,当使用 std::string 调用 GetHTTPMessage 时出现此错误:

'overloaded-function': 非法 sizeof 操作数

注意:参见类模板实例化“has_push_back”的参考 正在编译 和 [ T=std::字符串 ]

我不明白为什么它不能编译。

【问题讨论】:

    标签: c++ templates sfinae


    【解决方案1】:

    SFINAE is not yet properly supported in VS2015

    虽然这似乎是可能的(请注意,我只检查是否存在特定的过载):

    #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
    

    【讨论】:

    • 你说得对,VS2015 不能正确支持 SFINAE,但我用不同的方法解决了我的问题。谢谢。
    • 也许你把它贴在这里作为另一个答案呢?
    • 不,它确实解决了我的问题,但没有回答我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多