【问题标题】:C++ std::set metaprograming set of set of set ... nestingC++ std::set 元编程 set of set ... 嵌套
【发布时间】:2020-02-14 08:09:27
【问题描述】:

我试图从数学基础有序对开始从头开始实现一个 n 元组 其中 n 元组 (a,b,c) = ordered_pa​​ir(a,ordered_pa​​ir(b,c)) 和有序对是一个集合表示 IE。 ordered_pa​​ir(a,b) = 设置{{a},{a,b}}

这里是ordered_pa​​ir的代码

#include <iostream>
#include <set>
#include <boost/variant.hpp>
using namespace std;
template <typename T, typename U, typename Z>
class orderd_pair{

//typedef boost::variant<int,std::string,double> cell;
private:
set<set<Z>> opair;

set<T> first;
set<U> second;

public:

set<set<Z>> Orderd_pair(T first_element, U second_element){

first.insert(first_element);
second.insert(first_element);
second.insert(second_element);
opair.insert(first);
opair.insert(second);

return opair;

}
//TO DO void print_elements(std::set<std::set<cell>> opair);*/

};

问题是当试图实现每个ordered_pa​​ir的元组集时必须嵌套,即 对于三元素元组集{{a},{a,{{b},{b,c}}}} 和更多元素,它将嵌套更多,使其难以使用,我该如何解决这个问题?

我还使用 boost::variant 来支持 int、std::string 和 double 数据类型。

【问题讨论】:

  • 你为什么要这样做?如果它很难使用,为什么不使用std::tuple
  • 您是故意将您的实现限制在int, std::string, double 还是您只是不知道如何使其通用?它们是否真的应该是可互换的(即是否允许用 int 替换字符串,因为这就是变体正在做的事情)

标签: c++ templates metaprogramming stdset


【解决方案1】:

如果TU 不同,您很快就会发现不能将std::set&lt;T&gt;std::set&lt;U&gt; 放入同一个容器中。所以你很可能最终得到 ​​p>

struct any_less {
    bool operator()(const std::any & lhs, const std::any & rhs) { 
        return type_index(lhs.type()) < type_index(rhs.type()); 
    }
}

using ordered_pair = std::set<std::set<std::any, any_less>>;

编码你的重复关系。

template <typename A, typename B>
ordered_pair make_ordered_pair(A a, B b) {
    return { { a }, { a, b } };
}

template <typename A, typename B, typename C, typename... Rest>
ordered_pair make_ordered_pair(A a, B b, C c, Rest... rest) {
    return { { a }, { a, make_ordered_pair(b, c, rest...) } };
}

但是对于有序对,C++ 有一个更好的类型:std::pair。它还有一个更好的元组类型:std::tuple

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2010-11-24
    相关资源
    最近更新 更多