我想检查一个类型是否来自特定的命名空间.这是我想出的:
#include <utility>
namespace helper
{
template <typename T, typename = void>
struct is_member_of_sample : std::false_type
{
};
template <typename T>
struct is_member_of_sample<
T,
decltype(adl_is_member_of_sample(std::declval<T>()))> : std::true_type
{
};
}
namespace sample
{
template <typename T>
auto adl_is_member_of_sample(T && ) -> void;
}
// -- Test it
namespace sample
{
struct X;
}
struct Y;
static_assert(helper::is_member_of_sample<sample::X>::value, "");
static_assert(not helper::is_member_of_sample<Y>::value, "");
int main(){}
Run Code Online (Sandbox Code Playgroud)
只要没有人添加adl_is_member_of_sample到自己的命名空间(甚至是全局命名空间),这样就可以正常工作.当然,我必须为我想要测试的每个命名空间创建这样的构造.
如果类型来自特定名称空间,是否有更好的方法在编译时检查?
在EDSL中,我在编译时检查类型特征,以查看某些表达式是否有效.其中一些类型特征非常简单:如果一个类有一个using is_numeric = void,那么我将它视为一个数字表达式.工作良好.
is_numeric虽然非常通用.其他人也可能会使用它.因此,我考虑通过检查类型是否来自预期的命名空间来支持特征.
我有一个中等大小的代码库(> 200 .cpp),它使用一个函数hashCode()来返回哈希值: -
class B01{ //a class
//..... complex thing ....
public: size_t hashCode(){ /* hash algorithm #H01 */}
};
class B02{ //just another unrelated class
//..... complex thing ....
public: size_t hashCode(){/* #H02 */} //This is the same name as above
};
Run Code Online (Sandbox Code Playgroud)
我已在各种位置使用它,例如在我的自定义数据结构中.它运作良好.
现在,我想让std::数据结构识别哈希算法: -
这是我应该做的: - (从cppreference修改,我将调用此代码#D).
//#D
namespace std {
template<> struct hash<B01> {
std::size_t operator()(const B01& b) const {
/* hash algorithm #H01 */
}
}; …Run Code Online (Sandbox Code Playgroud)