【问题标题】:C++ if constexpr vs template specializationC ++ if constexpr 与模板专业化
【发布时间】:2022-01-10 15:32:13
【问题描述】:

考虑这两个例子

示例 1

template<Type type>
static BaseSomething* createSomething();

template<>
BaseSomething* createSomething<Type::Something1>()
{
     return Something1Creator.create();
}

template<>
BaseSomething* createSomething<Type::Something2>()
{
     return Something2Creator.create();
}

.... // other somethings

示例2

template<Type type>
static BaseSomething* createSomething() 
{
    if constexpr(type == Type::Something1)
    {
        return Something1Creator.create();
    }
    else if constexpr(type == Type::Something2)
    {
        return Something2Creator.create();
    }
    // Other somethings
}

我知道这两个示例在概念上是相同的,但考虑到这些函数位于 SomethingFactory.hpp 文件中,而我的 main.cpp 包含它。

main.cpp 中,我可能只创建Something1 类型而不知道存在其他Something 类型。

最后我真的关心我的可执行文件的大小。您认为我应该采用哪种模式使我的可执行文件最小化?或者这些没什么大不了的,反正我们都注定要失败?

【问题讨论】:

    标签: c++ templates compile-time specialization if-constexpr


    【解决方案1】:

    您认为我应该采用哪种模式来使我的可执行文件最小化?

    在这两种情况下,如果您只实例化createSomething&lt;Type::Something1&gt;,您将获得一个函数定义,实际上是一行代码。

    我真的最终会关心我的可执行文件的大小

    然后摆脱static。模板函数是隐式内联的,但static 函数对于每个翻译单元都有唯一的副本。

    我知道这两个例子在概念上是一样的

    他们不是。

    createSomething&lt;void&gt; 是使用 Example2 定义的函数,使用 Example 1 未定义。

    【讨论】:

    • 我没有得到这一行 createSomething 是使用示例 2 定义的函数,并且使用示例 1 未定义。 为什么在示例 2 中定义了 `createSomething而不是在示例 1 中?
    • @TheScore 你熟悉什么是“函数定义”吗?可以在Example2中指向createSomething&lt;void&gt;的定义位置,但是在Example 1中不能指向它,因为它不存在。
    • 知道了。谢谢你。您的评论导致帖子说 模板是编译器用来生成一系列类或函数的“模式”。为了让编译器生成代码,它必须同时查看模板定义(不仅仅是声明)和特定类型/用于“填充”模板的任何内容。 因为在带有定义的 Example2 模板 func 中,它会标记不同类型的工具。我猜对了吗?
    • @TheScore 我相信是的。
    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多