函数模板参数
Function template parameter
我遇到了下面的代码,它在类中定义了一个函数模板:
#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 '的实现令人困惑。代码按原样编译,因此语法必须正确。然而,这个方法没有从程序的任何其他部分调用,所以我不确定这个函数的意图是什么(缺乏文档)。我想这个函数可能有两种解释:
根据对象的魔幻类型和作为函数模板形参传递的特定枚举类型返回true/false。
。该方法的调用将是:
foo bar(1.2, foo::magic_type::BLUE); bool temp = bar.is_of_type<foo::magic_type::BLUE>(&(bar.header));
然而,在上面的例子中,我并没有真正传递类型(如int或char等)。对吧?
如果魔术类型是一个有效的枚举,则返回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
,一次用于静态变量,这是非常令人困惑的。
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 具有常量引用参数的函数模板专用化
- 使用可变参数函数作为模板参数
- std::span<const T> 作为函数模板中的参数
- 如何在C++中伪造虚拟可变参数函数模板?
- C++ std::functional 中的可变参数函数模板
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 三个参数函数模板令人困惑的示例
- 父可变参数函数模板专门用于子级
- C++如何将可变参数函数模板的参数包 -> 包装到 lambda 中
- 将函数传递给可变参数函数模板
- 为什么可变参数函数模板中的这个 constexpr 不是常数?
- 将多个初始值设定项列表传递到可变参数函数模板时遇到问题
- 依赖类型不明确的 c++11 可变参数函数模板重载是否不明确
- 操作可变参数函数模板的函数参数
- C++11 中的非类型可变参数函数模板
- 将可变参数函数模板的每个参数传递给返回void的函数
- 包扩展不在最后一个参数中的可变参数函数模板
- 将可变参数函数模板参数存储到联合向量中的最有效方法
- Clang 和 GCC 在解决可变参数函数模板重载时的行为不同