我正在尝试创建一个名为 Choose
的函数,它可以将以下内容作为参数:
template<typename... Args>
class Option
{
Option(Args... arguments)
{
// irrelevant
}
// ...
}
void Foo()
{
Choose(
Option<int, int>(3, 5),
Option<int>(7,123),
Option<int, int, int, int>(1, 2, 3, 4)
);
}
因此,我有一个具有可变类型的类,并且我想创建一个函数,该函数接受该类的任意数量的实例,其中每个实例的类型都可以有不同
参数。
我能够创建这样一个函数,其中所有实例的类型都需要具有相同的参数:
template <template <typename... Args> class... Opt, typename... Args>
void Choose(EnemyAIState& state, Opt<Args...>... option)
{
// irrelevant
}
void Foo()
{
Choose(state,
Option<int>(1),
Option<int>(2),
Option<int>(3)
);
}
但是,我无法实现最终目标,因为我找不到正确的语法
来使用。我希望你能帮助我朝正确的方向发展。
最佳答案
我认为你不能直接做你想做的事 - 你需要像“包的包”之类的东西,但没有这样的东西。
如果您想要更好的错误消息,请编写一个 static_assert
来测试传入的每种类型是否为 Option
:
// helper template that checks all of values are true
template<bool... values>
struct all_true;
template<>
struct all_true<> : std::true_type { };
template<bool b, bool...values>
struct all_true<b, values...> : std::integral_constant<bool, b && all_true<values...>::value> { };
template<typename... Args>
struct Option
{
Option(Args... /*arguments*/)
{
// irrelevant
}
// ...
};
// trait class that tests that a type is an Option
template<typename T>
struct is_option : std::false_type { };
template<typename... Args>
struct is_option<Option<Args...>> : std::true_type { };
template <typename... Opt>
void Choose(Opt... arguments)
{
// check that each type is an Option
static_assert(all_true<is_option<Opt>::value...>::value, "Arguments must all be Options");
// irrelevant
}
Demo .
关于c++ - 可变参数模板类的可变参数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25416952/