gpt4 book ai didi

c++ - 我应该更喜欢通过嵌套的 typedef 还是继承来调用模板元函数?

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

我可以编写一个递归的 Contains 元函数,通过继承或嵌套的 typedef 调用自身。以下标准有何不同(如果有)?

A:编译时间和编译时需要的内存。

B:最大递归限制(一个允许我使用比另一个更多的参数吗?)

C:惰性实例化(是否允许我省略更多实例化?这在当前示例中可能没有什么不同。但是,如果一个类嵌套了 std::conditional 的 typedef vs是从它派生出来的吗?)

1:

template<typename T, typename... Ts>
struct Contains : std::false_type {}; //only possible if Ts is empty so does not contain
template<typename T, typename U, typename... Ts>
struct Contains<T, U, Ts...> : Contains<T, Ts...>{};
template<typename T, typename... Ts>
struct Contains<T, T, Ts...> : std::true_type{};

2:

template<typename T, typename... Ts>
struct Contains {
typedef std::false_type Type;
}; //only possible if Ts is empty so does not contain
template<typename T, typename U, typename... Ts>
struct Contains<T, U, Ts...> {
typedef typename Contains<T, Ts...>::Type Type;
};
template<typename T, typename... Ts>
struct Contains<T, T, Ts...>{
typedef std::true_type Type;
};

最佳答案

我会使用继承,原因是它自然允许标签分派(dispatch):

template <typename T>
void f_impl(T const & t, std::true_type derivedB) { ... }
...
template <typename T>
void f(T const & t) {
f_impl(t, is_base_of<B,T>());
}

同时可以使用继承来插入嵌套信息,在这种情况下,::value 静态成员的计算结果为true.

关于c++ - 我应该更喜欢通过嵌套的 typedef 还是继承来调用模板元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19908996/

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