[英]Rewriting a parameter pack by replacing types
Here, I want to rewrite a variadic template parameter pack and replace occurrence of some type with another. 在这里,我想重写一个可变参数模板参数包,并将某种类型的出现替换为另一种。 Here is a pseudocode-like example: 这是一个类似伪代码的示例:
#include <string>
template <typename Params, typename Args>
struct TermRewrite {
template <typename... Body>
static auto constexpr eval(){
// Fill here...
}
};
int main() {
TermRewrite<int, char>::eval<int, std::string, double>();
// should give me pack of types as <char, std::string, double>
// ie. it should replace type int with char in Body...
}
So that I can chain these term rewrites in the end. 这样我就可以最终链接这些术语重写。 Basically, I want to transform the variadic template before forwarding it. 基本上,我想在转发可变参数模板之前对其进行转换。 How can I achieve this? 我该如何实现? I am not able to come-up with a solution. 我无法提出解决方案。 For all you want to know, this is a made-up exercise for myself. 对于所有您想知道的,这是我自己的虚构练习。 Also, do you have any suggestions on usability so that it is easier to chain TermRewrite
calls? 另外,您是否对可用性有任何建议,以便更轻松地链接TermRewrite
调用?
You use parameter pack expansion with a metafunction taking a single argument 您可以对带有单个参数的元函数使用参数包扩展
template<typename From, typename To>
struct replace
{
template<typename T>
using replace_fn = std::conditional_t<std::is_same_v<From, T>, To, T>;
template<typename... Args>
using apply = std::tuple<replace_fn<Args>...>;
};
Note you have to save the result as a template taking parameter packs like std::tuple
. 请注意,您必须将结果保存为带有参数包(如std::tuple
的模板。
If you want to chain the replacement, you could write 如果要链接替换,您可以编写
template<typename From, typename To, typename... Args>
struct replace_impl
{
template<typename T>
using replace_fn = std::conditional_t<std::is_same_v<From, T>, To, T>;
using type = std::tuple<replace_fn<Args>...>;
};
template<typename From, typename To, typename... Args>
struct replace_impl<From, To, std::tuple<Args...>>
{
template<typename T>
using replace_fn = std::conditional_t<std::is_same_v<From, T>, To, T>;
using type = std::tuple<replace_fn<Args>...>;
};
template<typename From, typename To>
struct replace
{
template<typename... Args>
using apply = typename replace_impl<From, To, Args...>::type;
};
And use as 并用作
replace<char, float>::apply<replace<int, char>::apply<int, char, bool>>
But be careful that this means you are treating a single std::tuple
not as a type, but a list of types. 但是要小心,这意味着您将把一个std::tuple
当作一个类型,而不是一个类型列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.