检测类型是否为 std::tuple?

2022-01-20 00:00:00 tuples templates c++ c++11 typetraits

目前我有两个功能:

template<typename Type> bool f(Type* x);
template<typename... List> bool f(std::tuple<List...>* x);

有什么方法可以将这两个函数与一个额外的模板参数合并,该参数指示传递的类型是否为元组?

Is there any way to merge these two functions with an extra template parameter that indicates whether the passed type is a tuple ?

template<typename Type, bool IsTuple = /* SOMETHING */> bool f(Type* x);

推荐答案

当然,使用 is_specialization_of(链接取自 这里):

template<typename Type, bool IsTuple = is_specialization_of<Type, std::tuple>::value>
bool f(Type* x);

然而,问题是,你真的想要这样吗?通常,如果您需要知道一个类型是否是元组,您需要对元组进行特殊处理,这通常与它的模板参数有关.因此,您可能希望坚持使用重载版本.

The question is, however, do you really want that? Normally, if you need to know if a type is a tuple, you need special handling for tuples, and that usually has to do with its template arguments. As such, you might want to stick to your overloaded version.

既然你提到你只需要一小部分专门化,我建议重载,但只适用于小的特殊部分:

Since you mentioned you only need a small portion specialized, I recommend overloading but only for the small special part:

template<class T>
bool f(T* x){
  // common parts...
  f_special_part(x);
  // common parts...
}

template<class T>
void f_special_part(T* x){ /* general case */ }

template<class... Args>
void f_special_part(std::tuple<Args...>* x){ /* special tuple case */ }

相关文章