gpt4 book ai didi

c++ - Variadic 模板基类调用转移

转载 作者:可可西里 更新时间:2023-11-01 17:41:44 26 4
gpt4 key购买 nike

在 pre-11 C++ 中我有这样的东西:

template<class T,class U,class V>
struct Foo : T,U,V {

bool init() {

if(!T::init() || !U::init() || !V::init())
return false;

// do local init and return true/false
}
};

我想将其转换为 C++11 可变参数语法以获得灵活长度参数列表的好处。我理解使用递归解压模板 arg 列表的概念,但我看不到正确的语法。这是我尝试过的:

template<typename... Features>
struct Foo : Features... {

template<typename F,typename... G>
bool recinit(F& arg,G&& ...args) {

if(!F::init())
return false;

return recinit<F,G...>(args...);
}

bool init() {
// how to call recinit() from here?
}
};

我更喜欢从左到右调用基类 init() 函数的顺序,但这并不重要。

最佳答案

这应该有效:

template<typename F, typename... T>
struct recinit;

template<typename F>
struct recinit<F> {
static bool tinit(F *) {
return true;
}
};
template<typename F, typename T, typename... G>
struct recinit<F, T, G...> {
static bool tinit(F *ptr) {
if (!ptr->T::init())
return false;
return recinit<F, G...>::tinit(ptr);
}
};

template<typename... Features>
struct Foo : Features... {

bool init() {
bool res = recinit<Foo, Features...>::tinit(this);
//use res wisely
}
};

你的问题是你不能写函数的偏特化,只能写类/结构。并且辅助结构必须在 Foo 之外,否则它将从封闭结构中获取模板参数,这将很糟糕。

你没有说,但我假设 init 是一个非静态成员函数。如果是这样的话,args 参数就没有意义了:它们都应该是 this!所以只要过去一次并避免参数中的包。我尝试将 this 作为 void* 传递,但这可能很麻烦,所以我只是向 recinit 添加了一个额外的模板参数,它将是 Foo.

而且,每次执行一个递归步骤时,请记住删除一个参数。

关于c++ - Variadic 模板基类调用转移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15295874/

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