gpt4 book ai didi

C++ typedef 需要::type

转载 作者:行者123 更新时间:2023-11-28 06:02:09 24 4
gpt4 key购买 nike

尝试从 BGL 开始,这意味着我从很多 typedef 开始:

#include <iostream> //std::cin, std::cout
#include <tuple> //std::tie

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>

using namespace boost;
typedef adjacency_list<vecS,vecS,undirectedS,no_property,property<edge_weight_t,int> > Graph;
typedef graph_traits<Graph> Traits;
typedef Traits::vertex_descriptor Vertex;
typedef Traits::edge_descriptor Edge;
typedef property_map<Graph, edge_weight_t>::type EdgeWeightMap; //::type necessary (why?)

int main(int argc, char* argv[]){
int n = ...;
Graph g(n);
EdgeWeightMap weight_of;
Edge e;
bool success;
int s,t,w;
std::cin >> s >> t >> w;
tie(e,success) = add_edge(s,t,g);
if(success)weight_of[e] = w;
}

我想知道为什么 ::typeEdgeWeightMap 的类型定义中是必要的。如果我省略它,我会得到

error: no match for ‘operator[]’ (operand types are

‘EdgeWeightMap {aka boost::property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> >, boost::edge_weight_t>}’

and

‘Edge {aka boost::detail::edge_desc_impl<boost::undirected_tag, unsigned int>}’

) weight_of[e] = w;

(对格式感到抱歉,typedefs 的 <> 似乎干扰了 block 引用)

确实,当我尝试

EdgeWeightMap weight_of = get(edge_weight,g);

我得到一个

error: conversion from

‘boost::detail::adj_list_any_edge_pmap::bind_<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> >, boost::property<boost::edge_weight_t, int>, boost::edge_weight_t>::type {aka boost::adj_list_edge_property_map<boost::undirected_tag, int, int&, unsigned int, boost::property<boost::edge_weight_t, int>, boost::edge_weight_t>}’

to non-scalar type

‘EdgeWeightMap {aka boost::property_map<boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> >, boost::edge_weight_t>}’

requested EdgeWeightMap weight_of = get(edge_weight,g);

现在,我可以看到这些是不同的类型,但我不明白的是为什么它们不同。由于我有点想避免意外,有人可以告诉我什么时候 ::type是必需的,什么时候不能使用?

最佳答案

来自阅读property_map文档中,“property_map”模板旨在提供类型,而不是类型。 property_map 结构恰好包含两种类型。 typeconst_type,分别用于可变类型和不可变类型。

关于C++ typedef 需要::type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056430/

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