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

问题描述 投票:13回答:5

目前我有两个功能:

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

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

template<typename Type, bool IsTuple = /* SOMETHING */> bool f(Type* x);
c++ templates c++11 tuples typetraits
5个回答
13
投票

当然,使用is_specialization_of(从here获取并修复的链接):

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

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

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

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

7
投票

使用C ++ 17,这是一个使用if constexpr的相当简单的解决方案

template <typename> struct is_tuple: std::false_type {};

template <typename ...T> struct is_tuple<std::tuple<T...>>: std::true_type {};

然后你可以这样做:

template<typename Type> bool f(Type* x) {
    if constexpr (is_tuple<Type>::value) {
        std::cout << "A tuple!!\n";
        return true;
    }

    std::cout << "Not a tuple\n";
    return false;
}

确保其有效的测试:

f(&some_tuple);
f(&some_object);

输出:

元组!! 不是一个元组


解决方案部分来自这里发现的answerHow to know if a type is a specialization of std::vector?


5
投票

您可以让您的函数遵循另一个函数:

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

template<typename Type> 
inline bool f(Type* x) { return f<Type,false>(x); }

template<typename... List> 
inline bool f(std::tuple<List...>* x) { return f<std::tuple<List...>,true>(x); }

3
投票

使用C ++ 11,这是我的首选模式:

// IsTuple<T>()
template <typename T>
struct IsTupleImpl : std::false_type {};

template <typename... U>
struct IsTupleImpl<std::tuple <U...>> : std::true_type {};

template <typename T>
constexpr bool IsTuple() {
  return IsTupleImpl<decay_t<T>>::value;
}

效果很好。没有依赖(我不能使用Boost)。


2
投票

可能会有点晚,但您也可以使用模板变量以更现代的c ++ 17样式执行此类操作:

template <typename T>
constexpr bool IsTuple = false;
template<typename ... types>
constexpr bool IsTuple<std::tuple<types...>>   = true;

还有一些测试

struct TestStruct{};

static_assert(IsTuple<int> == false,                "Doesn't work with literal.");
static_assert(IsTuple<TestStruct> == false,         "Doesn't work with classes.");
static_assert(IsTuple<std::tuple<int, char>>,       "Doesn't work with plain tuple.");
static_assert(IsTuple<std::tuple<int&, char&>>,     "Doesn't work with lvalue references");
static_assert(IsTuple<std::tuple<int&&, char&&>>,   "Doesn't work with rvalue references");

你可以在这里查看https://godbolt.org/z/FYI1jS

编辑:您将要运行std :: decay,std :: remove_volatile,std :: remove_const来处理特殊情况。

© www.soinside.com 2019 - 2024. All rights reserved.