有人可以向我解释以下模板代码吗?

问题描述 投票:0回答:1

我是模板编程的新手,我打算在这里使用该解决方案来确保所使用的类型已定义了运算符。但我想了解这段代码。我查看了cppreference的信息,但对它的工作方式更加困惑。

How to check whether operator== exists?

不幸的是,这对我来说很神秘,以为会询问代码中某些内容的含义和原因。

namespace CHECK
{
    struct No {};
    template <typename T, typename Arg>
    No operator==(const T&, const Arg&);

    /* Why are there two definitions of structures? Is this needed at all? Is
     * there a simpler version of this whole code snippet?
     */
    template <typename T, typename Arg = T>
    struct EqualExists {
        /* Why does this have to be a enum? What effect does this have? */
        enum {
            /* What happens if == sign is not defined for T? What would the
             * below comparison return when true/false? (The comparision *(T*)(0) == *(Arg*)(0))
             *
             * What is the need for No here? Why is it needed and how will
             * comparing it with the return type of == comparison be true ever?
             * How can the return type of == comparison and No structure be the same?
             */
            value = !std::is_same<decltype(*(T*)(0) == *(Arg*)(0)), No>::value
        };
    };
}

有人可以将其链接到原始问题吗?希望这可以帮助刚接触cpp的人也了解这一点。

提前谢谢您:)

c++ templates
1个回答
0
投票

说明

© www.soinside.com 2019 - 2024. All rights reserved.