j*****y 发帖数: 22 | 1 我有以下class:
class T{};
class A{
public:
A(int a, double b, T *t): a_(a), b_(b), t_(t) {}
private:
int a_;
double b_;
T *t_;
};
然后我要create A 的instances如下:
1)如果已经create过了相同的instance with the same a, b and t, return
existing instance (pointer)
2)如果1)不成立create一个新的instance
为了实现1),怎样可以check某一个A的constructor input argument的组合已经见过
了?有什么hash function可以同时hash几个不同type的变量吗?
多谢高手! |
y*****g 发帖数: 5 | 2 如果是C++11或以上的话,可以加一段std::hash>的specialization:
------------------------------------------
namespace std {
template
struct hash> {
template
inline static std::size_t CombineHashes(const TupleT &arg,
std::enable_if_t* = 0) {
std::size_t first_hash = CombineHashes(arg);
std::size_t second_hash = std::hash<
typename std::tuple_element::type>()(std::get(arg)
);
// http://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x
return first_hash ^
(second_hash + 0x9e3779b9 + (first_hash << 6) + (first_hash >> 2));
}
template
inline static std::size_t CombineHashes(const TupleT &arg,
std::enable_if_t* = 0) {
return 0;
}
inline std::size_t operator()(const std::tuple &arg) const {
return CombineHashes(arg);
}
};
}
------------------------------------------
然后你就可以用std::unordered_map了:
std::unordered_map, std::unique_ptr>
instances; |
N*****m 发帖数: 42603 | 3 用boost的hash_combine也可以
specialization:
【在 y*****g 的大作中提到】 : 如果是C++11或以上的话,可以加一段std::hash>的specialization: : ------------------------------------------ : namespace std { : template : struct hash> { : template : inline static std::size_t CombineHashes(const TupleT &arg, : std::enable_if_t* = 0) { : std::size_t first_hash = CombineHashes(arg); : std::size_t second_hash = std::hash<
|
j*****y 发帖数: 22 | |
s*******i 发帖数: 698 | |
S*******s 发帖数: 13043 | 6 template< class T1, class T2 >
class NamedSingleton{
protected:
NamedSingleton(){};
public:
static T1& GetInstance(const T2& name){
static std::map instances;
typename std::map::iterator ite=instances.find(name);
if(ite==instances.end()){
instances.insert(std::pair(name,T1(name)));
ite=instances.find(name);
}
return (ite->second);
}
private:
};
class A:public NamedSingleton >{
...
} |