gpt4 book ai didi

c++ - 创建一系列显式函数模板实例化

转载 作者:太空狗 更新时间:2023-10-29 20:54:07 27 4
gpt4 key购买 nike

在 C++ 11 中,我能否构建一个模板,将一系列函数模板显式实例化为数组初始化程序?我想要实现的目标(请不要问我为什么需要那个,因为这是一个很长的故事)看起来像

// The template I want to instantiate:
template<size_t N> void callbackTemplate(const int dummy) {
// Do something which needs to know 'N'.
}

// The variable I want to assign 'callbackTemplate' instantiations to:
void (*callback)(const int dummy); // This cannot be std::function, because it
// is not defined by me! It is already there and
// must be used as it is.

// This is the set of instantiations I want to prepare:
std::array<decltype(callback), 3> callbackTemplates = {
callbackTemplate<0>, callbackTemplate<1>, callbackTemplate<2>
};

上面的代码按原样工作。我想要更改的是 callbackTemplates 数组的初始化。我希望初始化程序成为一个模板,该模板依赖于编译时常量并创建实例化 0..N。

这个问题在某种程度上与C++ static const array initialization in template class有关,但我没有设法“模板化”另一个模板的实例化。

最佳答案

您可以使用 C++14 的 std::integer_sequence 实现来做到这一点。 Here 的。

callback_t 定义为

using callback_t = decltype (callback);

你可以只传递一个序列并使用类型推导:

template<unsigned... Is>
array<callback_t, sizeof...(Is)> make_callback_array_impl(seq<Is...>)
{
return { callbackTemplate<Is>... };
}

template<unsigned N>
array<callback_t, N> make_callback_array()
{
return make_callback_array_impl(GenSeq<N>{});
}

live demo

关于c++ - 创建一系列显式函数模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com