1

我想要std::tuple一个特定大小的函数,并提供一个函数,该函数接受与元组一样多的参数并且具有相同的确切类型。

我想我可以使用可变参数模板函数从参数包中构造一个元组并将这两个元组与std::is_same

下面是一些示例代码来进一步解释我的尝试

#include <tuple>
#include <iostream>
#include <string>
#include <typeinfo>

static const auto TupleInts =
     std::make_tuple(
        1,
        2,
        3
    );

static const auto TuplePairs =
    std::make_tuple(
        std::make_pair(1, 1),
        std::make_pair(2, 2),
        std::make_pair(3, 3)
    );

typedef decltype(TupleInts) TupleIntsType;
typedef decltype(TuplePairs) TuplePairsType;
typedef std::tuple<int, int, int> TupleType;

template<typename... Ts>
bool compare(Ts... vals) {
    std::cout << typeid(std::tuple<Ts...>).name() << std::endl;
    std::cout << typeid(TupleType).name() << std::endl;

    return std::is_same < std::tuple<Ts...>, TupleType >::value;
}

template<typename... Ts>
bool comparePairsTuple(Ts... vals) {
    std::cout << typeid(std::tuple<std::pair<int, Ts>...>).name() << std::endl;
    std::cout << typeid(TuplePairsType).name() << std::endl;

    return std::is_same < std::tuple<std::pair<int, Ts>...>, TuplePairsType >::value;
}

template<typename... Ts>
bool compareIntsTuple(Ts... vals) {
        std::cout << typeid(std::tuple<Ts...>).name() << std::endl;
    std::cout << typeid(TupleIntsType).name() << std::endl;

    return std::is_same < std::tuple<Ts...>, TupleIntsType >::value;
}

int main() {
    std::cout << comparePairsTuple(1, 2, 3) << std::endl;
    std::cout << compareIntsTuple(1, 2, 3) << std::endl;
    std::cout << compare(1, 2, 3) << std::endl;

    return 0;
 }

这是我在 Visual Studio 2013(vc120) 下得到的

class std::tuple<struct std::pair<int,int>,struct std::pair<int,int>,struct std::pair<int,int> >
class std::tuple<struct std::pair<int,int>,struct std::pair<int,int>,struct std::pair<int,int> >
0
class std::tuple<int,int,int>
class std::tuple<int,int,int>
0
class std::tuple<int,int,int>
class std::tuple<int,int,int>
1

在 GCC 5.2.0 下

St5tupleIJSt4pairIiiES1_S1_EE
St5tupleIJSt4pairIiiES1_S1_EE
0
St5tupleIJiiiEE
St5tupleIJiiiEE
0
St5tupleIJiiiEE
St5tupleIJiiiEE
1

为什么前两个 is_samefalse和最后一个true

4

2 回答 2

2

在前两种情况下,您使用std::is_same比较的类型具有不同的 const 限定条件。std::is_same仅当给定类型相同并且它们具有相同的 const-volatile 限定时才给出 true。请参阅http://en.cppreference.com/w/cpp/types/is_same

例如:

static const auto TupleInts =
     std::make_tuple(
        1,
        2,
        3
    );

typedef decltype(TupleInts) TupleIntsType;

template<typename... Ts>
bool compareIntsTuple(Ts... vals) {
        std::cout << typeid(std::tuple<Ts...>).name() << std::endl;
    std::cout << typeid(TupleIntsType).name() << std::endl;

    return std::is_same < std::tuple<Ts...>, TupleIntsType >::value;
}

TupleInts被声明为const并且在函数compareIntsTuple中它与非 const 的std::tuple进行比较。

于 2016-01-10T20:51:40.540 回答
0

typeid丢弃顶级 cv 限定符,std::is_same不丢弃。

要使其工作,请添加const以下一个或两个参数is_same

return std::is_same <const std::tuple<std::pair<int, Ts>...>,
                     const TuplePairsType >::value;
于 2016-01-10T20:53:55.797 回答