gpt4 book ai didi

c++ - 结合类模板默认参数和可变参数

转载 作者:太空狗 更新时间:2023-10-29 22:56:08 29 4
gpt4 key购买 nike

我正在设计一个 Host 类,它使用固定数量的 Policies 类,大约 3 或 4 个。

因为对于设计中的每个 Policy 总会有一个简单的实现,最好将模板参数默认为简单类型,以简化 的使用由其客户主办类(class)。

class IdiotBenchPolicy {};
class IdiotLoggerPolicy {};
// ...

template <typename BenchmarkPolicy = IdiotBenchPolicy,
typename LoggerPolicy = IdiotLoggerPolicy>
class Host
{
BenchmarkPolicy m_bench;
IdiotLoggerPolicy m_logger;
};

这允许实例化一个Host,而无需指定一长串模板参数。

这很好,直到 Host 类也必须采用可变数量的算术类型。拆分问题时,忘记了 Policies,我可以使用可变模板参数:

template <class... Args>
class Host
{
template <class ...Var_Args>
using are_arithmetic = typename std::conjunction<std::is_arithmetic<Var_Args>...>::type;

static_assert(are_arithmetic<Args...>::value, "Args are not all arithmetic type");
std::tuple<Args...> m_args;
};

请注意,即使 Host 在内部使用元组,除非必要,否则最好不要在类客户端上强制使用它。

我现在的问题是将这两种行为结合起来。如果“默认”已足够,如何实例化一个 Host 类而不必指定 Policies。我不确定如何使用 C++ 模板语法来表达这一点,但我的直觉告诉我可以通过使用 SFINAE 和 std::enable_if 来表达,但我很难看出如何。

我希望能够写的是:

Host<int, int, float> h; //Using both default policies
Host<SmarterBenchPolicy, float, double> h2; //Using SmarterBenchPolicy, IdiotLoggerPolicy and two arithmetic types
Host<SmarterBenchPolicy>; //Using SmarterBenchPolicy, IdiotLoggerPolicy and no arithmetic type

如何实现这样一个Host 类,它可以使用类似于上面指定的实例化来构造?

最佳答案

我觉得如果把那些默认值的参数放在参数列表的 和 会更好。可变参数可以打包到 std::tuple 中:

template <class ArgsPack,
typename BenchmarkPolicy = IdiotBenchPolicy,
typename LoggerPolicy = IdiotLoggerPolicy,
std::enable_if_t<detail::is_tuple<ArgsPack>::value, int> = 0
>
struct Host
{
BenchmarkPolicy bench;
LoggerPolicy logger;
ArgsPack args;

void show_all() {
detail::tuple_foreach([](const auto &e) {std::cout << e << "\n";}, args);
}
};

Host<std::tuple<int, int, float>, SmartBenchPolicy> h;

关于c++ - 结合类模板默认参数和可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48952448/

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