函数模板参数

Function template parameter

本文关键字:参数 函数模板      更新时间:2023-10-16

我遇到了下面的代码,它在类中定义了一个函数模板:

#include <cstdint>
class foo {
public:
    enum class magic_type : std::uint32_t {
        START = 0,
        BLUE = 0xFF000001,
        RED,
    };
    struct header_t {
        uint32_t version;
        magic_type magic;
    };
    template <typename T>
    static bool is_of_type(header_t *h)
    {
        return (h->magic == T::magic_type);
    }
    foo(uint32_t ver, foo::magic_type mag)
    {
        header.version = ver;
        header.magic = mag;
    }
    header_t header;
};

我发现'is_of_type '的实现令人困惑。代码按原样编译,因此语法必须正确。然而,这个方法没有从程序的任何其他部分调用,所以我不确定这个函数的意图是什么(缺乏文档)。我想这个函数可能有两种解释:

  1. 根据对象的魔幻类型和作为函数模板形参传递的特定枚举类型返回true/false。

    。该方法的调用将是:

    foo bar(1.2, foo::magic_type::BLUE);
    bool temp = bar.is_of_type<foo::magic_type::BLUE>(&(bar.header));
    

    然而,在上面的例子中,我并没有真正传递类型(如int或char等)。对吧?

  2. 如果魔术类型是一个有效的枚举,则返回true/false。

    在这种情况下,我假设函数不需要模板化,可以重写为:

    static bool is_of_type(header_t *h)
    {
        return (h->magic == foo::magic_type);
    }
    

    foo bar(1.2, foo::magic_type::BLUE);
    bool temp = bar.is_of_type(&(bar.header));
    

    再次出现编译错误。我尝试使用"typename",但是我的尝试是徒劳的。

有没有人可以帮助我正确实现上述两种情况下的is_of_type和一个调用示例。

调用将使用显式指定的类型,该类型具有嵌套的静态成员magic_type

例如,可以这样调用:

struct test {
    static foo::magic_type const magic_type;
};
foo::magic_type const test::magic_type = 42;
foo bar{1, foo::magic_type::BLUE};
bar.is_of_type<test>(bar.header);

magic_type被使用了两次,一次用于enum class,一次用于静态变量,这是非常令人困惑的。