我正在尝试使用 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/