c++ - 使用返回 constexpr 对进行模板实例化

标签 c++ templates c++17 constexpr

我正在尝试使用 std::pair 中的数据,该数据由 constexpr 自由函数返回。第一个元素确定 std::array 的大小,而第二个元素存储在数组中。

using DataBundle = std::pair<int, std::pair<int, int>>;

constexpr DataBundle get_data()
{
    // other work carried out here
    return std::make_pair(1, std::make_pair(2, 3));
}

struct x
{
    template<int size>
    using OtherData = std::array<std::pair<int, int>, size>;

    static constexpr OtherData<get_data().first> foo { get_data().second };
};

上面的代码并没有达到预期的效率,因为 get_data()foo 的实例化过程中被调用了两次。一种解决方案是将返回的数据存储为结构 x 的成员,如下所示。

// previous code remains the same

struct x
{
    template<int size>
    using OtherData = std::array<std::pair<int, int>, size>;

    static constexpr DataBundle foo_bundle = get_data(); 
    static constexpr OtherData<foo_bundle.first> foo { foo_bundle.second };
};

虽然这个解决方案似乎并没有充分利用模板机制。所以我的问题是,是否有更好的方法来充分利用上述每个示例?

最佳答案

实际上 constexpr 函数可能会被计算多次(而模板类应该只实例化一次),对于像您这样的简单情况,第一个片段就可以了。

虽然我会创建专用函数/lambda 来创建 foo:

struct x
{
    template<int size>
    using OtherData = std::array<std::pair<int, int>, size>;

    static constexpr auto foo = []() {
        constexpr DataBundle foo_bundle = get_data(); 

        return OtherData<foo_bundle.first>{foo_bundle.second};
    } ();
};

关于c++ - 使用返回 constexpr 对进行模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57436595/

相关文章:

c++ - 什么是 C++ 中的 <=> ("spaceship",三向比较)运算符?

c++ - 双指针可以用作二维数组吗

javascript - 如何在 Meteor.js #each 包装器中生成多个 SVG

c++ - 折叠表达式、参数包扩展、类成员函数中的递归

c++ - 字符串**数组;数组 [行] [列] = "string"上的段错误; C++

c++ - 在 C++98 和 C++11 中访问枚举值

C++ 从模板参数创建元组 vector

c++ - 模板特化还是条件表达式?

c++ - 将 std::bind 与 std::visit 一起使用

c++ - 由于存在默认成员初始化程序,因此类类型很简单