Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

c++ - Detect if a type is a std::tuple?

Currently I have two functions :

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, using is_specialization_of (link taken and fixed from here):

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.

Edit: 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...
}

with

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 */ }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...