gpt4 book ai didi

c++ - 访问图包属性类型,以在 SFINAE 中使用它

转载 作者:行者123 更新时间:2023-12-02 10:03:18 27 4
gpt4 key购买 nike

我有一些代码可以处理不同类型的(增强)图,我想为具有某些特定捆绑属性的图做一些特别的事情。

例如,这个:

struct VertexProp
{
// some data
};

我的代码可以使用两种类型的图表:
using graph1_t  = boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::undirectedS,
VertexProp
> ;

或者
using graph2_t = boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::undirectedS
> ;

我的意图是使用 SFINAE 来启用仅处理这种特定情况的功能:
template<Graph_t>
void foo
(
const Graph_t& gr,
std::enable_if<
std::is_equal<SOME_TRAIT<Graph_t>::type,VertexProp>,T
>::type* = nullptr
)
{
// do something only for graphs having VertexProp
}

在一般情况下,我对类型特征没意见(至少,我认为是...),但在这种情况下,它是第三方类型( boost::adjacency_list )。

而我在 the provided traits 中找不到typedef 给我那个类型。
我也查了 the included code在手册中,但没有帮助。

我如何访问该类型?

最佳答案

您可以通过 property_map 获取类型特征。事实上,值类型是该属性映射的一个特征:)

所以要检测顶点束:

template <typename Graph, typename Bundle = typename boost::property_map<Graph, boost::vertex_bundle_t>::type>
using VBundle = typename boost::property_traits<Bundle>::value_type;

使用空格使其更具可读性:
template <
typename Graph,
typename Bundle =
typename boost::property_map<Graph, boost::vertex_bundle_t>::type>
using VBundle =
typename boost::property_traits<Bundle>::value_type;

你可以看到我们问了 property_traitsvertex_bundle_t属性图。

要检查它是否是预期的类型:
template <typename Graph>
using HasVertexProp = std::is_same<VertexProp, VBundle<Graph> >;

现在您可以使用 SFINAE。或者,正如我所建议的那样:标签调度;
namespace detail {
template <typename Graph_t>
void foo(const Graph_t& g, std::true_type) {
print_graph(g, std::cout << "Graph with VertexProp bundle: ");
}

template <typename Graph_t>
void foo(const Graph_t& g, std::false_type) {
print_graph(g, std::cout << "Graph with other/missing properties: ");
}
}

template <typename Graph_t>
void foo(const Graph_t& g) {
detail::foo(g, HasVertexProp<Graph_t>{});
}

让我们测试一下:

Live On Coliru
int main() {
graph1_t g1(4);
graph2_t g2(4);
foo(g1);
foo(g2);
}

打印
Graph with VertexProp bundle: 0 <--> 
1 <-->
2 <-->
3 <-->
Graph with other/missing properties: 0 <-->
1 <-->
2 <-->
3 <-->

关于c++ - 访问图包属性类型,以在 SFINAE 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61486552/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com