是否可以使用宏或类似的东西来创建模板类的实例并生成代码,然后将创建的变量添加到使用
std::vector
的 std::variant
?
考虑这个例子:
#include <memory>
#include <variant>
#include <vector>
template <typename... Ts>
class Foo
{
};
int main()
{
// These definitions of Foo shall be produced by the macro
auto foo1 = std::make_shared<Foo<int, int, int>>(Foo<int, int, int>());
auto foo2 = std::make_shared<Foo<int, int>>(Foo<int, int>());
// The variants shall be done with respect to the instantiations of Foo
std::vector<std::variant<decltype(foo1), decltype(foo2)>> objects;
return 0;
}
foo1 和 foo2 两个创建了 Foo 类的两种类型,因为它们使用不同的模板参数。因此,
std::vector<std::variant<...>>
对象能够容纳两个变体。如果定义一个 foo3 的类型与之前的两个不同,那么它应该相应地带有三个变体。这可能吗?
或者宏通常无法处理输入数据类型?
您不需要在现代 C++ 中使用宏,因为您可以编写
constexpr
可变参数函数模板,如下所示:
template<typename... T>
constexpr auto make_foo()
{
return std::make_shared<Foo<T...>>();
}
auto foo1 = make_foo<int, int, int>();
auto foo2 = make_foo<int, int>();