【发布时间】:2020-01-28 19:30:22
【问题描述】:
在下面的代码示例中,我将通过run() 方法调用具有已初始化参数vect 的具体foo() 函数。对于编译,我使用 VS19 和 C++17。在下文中,我不确定我对std::apply 的使用...欢迎任何形式的帮助;)
#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
template<typename ...T>
struct Base {
vector<int> vect;
Base(){
static const std::size_t size = sizeof...(T);
for (int i = 0; i < size; i++)
vect.push_back((i+1)*(i+1)); //some initialization
}
};
template<typename ...T>
struct Derived : public Base<T...> {
virtual int foo(T...) = 0;
int lastResult;
void run() {
if (this->vect.size() > 0) {
lastResult = std::apply(foo, this->vect);
}else{
lastResult = -1;
cout << "0 arguments case" << endl;
}
}
};
struct D0 : public Derived<> {
int foo() override { return 0; }
};
struct D1 : public Derived<int> {
int foo(int a) override { return a * a; }
};
struct D2 : public Derived<int,int> {
int foo(int a, int b) override { return a + b; }
};
int main() {
D0 d0;
cout << d0.foo() << endl; // 0
//d0.run(); //vect = {}, lastResult = -1, "0 arguments case"
D1 d1;
cout << d1.foo(1) << endl; // 1
//d1.run(); //vect = {1} -> lastResult = 1
D2 d2;
cout << d2.foo(1, 2) << endl; // 3
//d2.run(); //vect = {1,4} -> lastResult = 5
cin.get();
}
【问题讨论】:
-
因为您在编译时就知道
vect中将存储多少元素,您可以使用std:array代替,这与std::apply相同。还是施工后需要改尺寸? -
@1201ProgramAlarm 谢谢你的回复。目前,对于我创建的对象类型,不需要更改它们的大小。但在该项目的未来,我也有兴趣在建设后可能扩大规模。您对此案有何建议?
标签: c++ variadic-templates virtual variadic-functions