【问题标题】:Find first underlying primitive in struct/class [duplicate]在结构/类中找到第一个基础原语 [重复]
【发布时间】:2016-09-09 07:58:54
【问题描述】:

前提:

我有一个可变参数模板函数,它接受具有同质成员类型的 POD(普通旧数据结构)。

可接受的 POD 可能完全由 4 字节整数 XOR 4 字节浮点数组成。

在内部,可变参数被强制转换为基础类型的指针并用作原始数组。

问题:

目前,模板功能需要用户提供一些关于这些 POD 格式的附加信息;比如下面的:

声明

template<typename ...U>
void foo(const char *format, U... bars);

用法

Blah much, wow; // Underlying type is integral.
Bleh such, params; // underlying type is float.
//... 
foo("iffi",much,params,such,wow);

它有效,但我想绕过格式化字符串。

问题:

有没有办法在编译时评估底层类型?

编辑:结构的布局及其成员的名称直到编译时才知道。也就是说,库的用户正在提供任意同构 POD。

【问题讨论】:

  • 请提供minimal reproducible example;这些结构到底是什么样子的? Blah、Bleh等有多少种不同的类型?
  • cmets 指定结构是具有统一/同质底层类型的 POD。问题指定类型由用户提供,因此库不知道。

标签: c++ templates typetraits


【解决方案1】:

要绕过字符串格式,您可以创建一个特征:

template <typename T /*, typename AlwaysVoidForSFINAE = void*/> struct UnderlyingPodType;

template <> struct UnderlyingPodType<Blah> { using type = int; };
template <> struct UnderlyingPodType<Bleh> { using type = float; };

template<typename ...Ts>
void foo(Ts&&... ts)
{
    using types = std::tuple<UnderlyingPodType<std::decay_t<Ts>>...>;
    // ...
}

【讨论】:

  • 结构的布局及其成员名称未知。
  • @EsmeraldaSalamone:我用这些新信息重写了一个答案。
  • 这需要为每种类型定义模板特化,这确实违背了我的目的。我不希望函数的用户必须为他们的类型提供这样的定义。
猜你喜欢
  • 1970-01-01
  • 2017-10-27
  • 2021-07-13
  • 2022-01-21
  • 2016-11-23
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多