我想知道我在哪里可以做这样的事情(c ++ 11):
//class FOO is a static class which contains static members and lots of typedefs for
container types such as vector, map, BOOST Graph (adjacency list), property_maps etc
current implementation:
// file: traits.hpp
class FOO {
typedef std::vector<int> container_t;
typedef std::map<int, int> map_t;
typedef boost::adjacency_list < > graph_t;
typedef boost::property_map < > p_map_t // syntax is not correct though(just for understanding purpose)
// lots of other typedefs ...
static int var1;
static int var2; // lots of other static variables
};
int FOO::var1 = 10;
int FOO::var2 = 20; //initialize static variables
// file BAR.hpp
template <class FOO>
class BAR {
public:
typedef typename FOO::map_t map_t;
typedef typename FOO::container_t conatiner_t; // and so on
typedef typename FOO::graph_t graph_t
BAR () { ... constructor ... }
private:
map_t my_map;
container_t my_container;
graph_t my_Graph;
};
Problem in above: lots of typedef typename need to be used always. Note that I
could directly use this in private: e.g.
typename FOO::map_t my_map;
typename FOO::graph_t my_graph;
but am avoiding it as there are lots of typenames and stuff which i will have
to manage and the code
//What I want to do :-->
// file: traits.hpp
// create a namespace "traits"
namespace traits {
class FOO {
typedef std::vector<int> container_t;
typedef std::map<int, int> map_t;
typedef boost::adjacency_list < > graph_t;
// lots of other typedefs
static int var1;
static int var2; // lots of other static variables
};
int FOO::var1 = 10;
int FOO::var2 = 20; //initialize static variables
}; // end namespace
// file BAR.hpp
using namespace traits;
class BAR {
public:
template <..>
void bar () // functions
private:
FOO::map_t my_map;
FOO::container_t my_container;
FOO::graph_t my_Graph;
}
OR would be like this :
private :
traits::FOO::map_t my_map;
traits::graph_t my_graph;
...
Cant I directly use like this as FOO will be the only class in namespace traits?
traits::map_t my_map;
traits::graph_t my_graph; //and so on...
我的主要动机是将所有typedef和静态变量保存在类(FOO)中并将其包装在命名空间(traits)中,这样我就不必将类FOO作为模板参数显式传递给类BAR,并且然后再次使用typedef,它不会使代码看起来很好,因为我有很多其他类使用FOO容器。同时我需要将容器typedef和static变量封装在一个类中。
有人可以帮帮我吗?谢谢!
答案 0 :(得分:0)
只需为特征创建自定义命名空间:
namespace traits
{
typedef std::vector<int> container_t;
typedef std::map<int, int> map_t;
typedef boost::adjacency_list < > graph_t;
typedef boost::property_map < > p_map_t // syntax is not correct though(just for understanding purpose)
};
class BAR {
public:
template <..>
void bar () // functions
private:
traits::map_t my_map;
traits::container_t my_container;
traits::graph_t my_Graph;
....
};