我正试图为我一直从事的类型家族提供一个hash<>专门化。到目前为止,专业化本身是很容易提供的,我已经为numeric_limits<>做了类似的事情。但我面临的问题是,如何以一种可移植到C++11和-pre-11 (C++03或其他什么)的方式提供专门化。
当然,我遇到的问题是,hash<>可以在几个名称空间中的一个中定义,而我被迫在同一个名称空间中提供专门化。
// in c++11
namespace std { struct hash<>...; }
// in c++03 this is one possibility
namespace std { namespace tr1 { struct hash<>...; } }
// my library's specialization
namespace ????_open {
struct hash<mytype>...;
????_close当然,一种选择是使用#defines来达到、打开和关闭适当的命名空间,或者提供N个文件具有N个不同的专门化,条件#包括正确的名称空间,但这很麻烦:
#if defined(some_c++11_condition)
#include "c++11-specialization.h"
#elif defined(some_c++03_condition)
#include "c++03-specialization.h"
#elif (some_other_condition)
#oh_dear_who_knows_what_this_include_will_be_like
#else_ad_nauseam
#endif当然,如果我被迫这样做的话,我会坚持这个策略,但我之前想探索一些其他的选择。特别是,我想我可以使用命名空间别名专门研究正确的位置:
#if defined(some_c++11_condition)
namespace std_specialize = std;
#elif defined(some_c++03_condition)
namespace std_specialize = std::tr1;
#...
#endif
...
namespace std_specialize {
struct hash<mytype>...;
}不幸的是,这在我尝试过的3种编译器(MSVC 2008、GCC 4.7、Clang3.0)中的任何一个都行不通,在重新打开名称空间的行中出现了与"declaration of namespace conflicts with...“有关的各种错误,这是不应该发生的,因为名称空间可以多次重新打开,如果别名是别名,而不是其他什么,那么这也应该适用于它们。
那么,名称空间别名是否真的是别名,还是用词不当意味着其他东西呢?还是有其他原因让我不能专攻这种方式?如果是的话,还有其他方法(比#定义的条形码更好)吗?
发布于 2013-09-26 20:02:04
是的,namespace别名实际上就是别名。出现此错误是因为您将std_specialize声明为std或std::tr1的别名,然后尝试使用相同的名称声明namespace。如果声明是合法的,那么在声明之后,std_specialize将引用什么、std(或std::tr1)或包含hash专门化的新命名空间?
你可能想做的是
namespace std {
#if __cplusplus < 201103L
namespace tr1 {
#endif
template<>
struct hash<my_type> { ... };
#if __cplusplus < 201103L
}
#endif
}发布于 2013-09-26 20:05:15
适当的宏:
// Defined before
// #define NOEXCEPT noexcept
#include <iostream>
#if TR1_CONDITION
// tr1
#define HASH_NAMESPACE std::tr1
#define HASH_NAMESPACE_BEGIN namespace std { namespace tr1 {
#define HASH_NAMESPACE_END }}
#else
// std
#define HASH_NAMESPACE std
#define HASH_NAMESPACE_BEGIN namespace std {
#define HASH_NAMESPACE_END }
#endif
namespace X {
struct Class {};
}
HASH_NAMESPACE_BEGIN
template<>
struct hash<X::Class> {
size_t operator()(const X::Class&) const NOEXCEPT { return 123; }
};
HASH_NAMESPACE_END
int main() {
HASH_NAMESPACE::hash<X::Class> h;
std::cout << h(X::Class()) << std::endl;
return 0;
}(但这一切都不太好)
https://stackoverflow.com/questions/19037113
复制相似问题