C++:绕过依赖模板的方法
我有一个这样的类模板:
template <typename T1, typename T2>
class ClassName {
// Members variables and Functions based on the template parameter types
};
(T1, T2)可以是(class A, class B)或(class C, class D)仅。因此,仅 T1 就足以确定 T2。有没有什么办法只把T1作为参数写同一个类?如果是,如何?
回答
如果您的模板仅依赖于单个参数,则不应使用 2 个参数声明它。您可以std::conditional与 with 一起使用std::is_same来声明条件别名。
如果你想:
(T1, T2) 只能是 (class A, class B) 或 (class C, class D)
如果“仅”的意思是:用户只为Aor实例化C,在这种情况下T2应该是B/ D:
#include <type_traits>
struct A {};
struct B {};
struct D {};
template <typename T>
struct Foo {
using T1 = T;
using T2 = std::conditional_t<std::is_same_v<A, T>, B, D>;
};
Foo<A>::T2是B并且Foo<C>::T2是D。实际上Foo<T>::T2是D为任何T不是A。换句话说,如上所述,前提是它仅针对A或实例化C。如果模板本身应该确保只有A或 的实例化C有效,您可能需要添加一个static_assert(再次std::is_same用于检查它T是否在允许的类型中)。
- I think `using T3 = T` would be valid too, little simpler.