我如何提取和使用 C++ 类的变量模板参数中定义的类型,而不是定义以下类的多个重复项,这些重复项仅按参数的数量和类型进行延迟:
template <typename T1, typename T2>
class SUTTestFixture
{
public:
void SetUp(T1 expected, vector<T2> data)
{
_expected = expected;
_data = data;
}
protected:
SUT _sutObj;
vector<T2> _data;
T1 _expected;
};
我希望能够仅使用带有变量模板参数的单个类:
template <typename... T>
class SUTTestFixture
{
public:
void SetUp(T... args)
{
_expected = args...[0];
_data = args...[1]; // expected ‘;’ before ‘...’ token
}
protected:
SUT _sutObj;
vector<T...> _data; // XXX
T... _expected; // error: expected unqualified-id before ‘...’ token
};
访问可变参数模板中的类型的一种方法是使用
std::tuple
。一旦定义了元组,您就可以访问其中的任何类型。示例:
#include <tuple>
#include <vector>
template <typename... T>
class SUTTestFixture
{
public:
// Get the types of the variadic T as a tuple
using types = std::tuple<T...>;
// Then you can access one specific type
using T1 = std::tuple_element_t<0,types>;
using T2 = std::tuple_element_t<1,types>;
void SetUp(T1 expected, std::vector<T2> data)
{
_expected = expected;
_data = data;
}
protected:
std::vector<T2> _data;
T1 _expected;
};
int main () {}