我有一个以对象为参数的方法
void fun(const Obj& obj)
Obj
可以用两种不同的方式定义:
struct Obj
{
Type x;
};
和
struct Obj
{
Type x[42];
};
我不能修改 Obj
的定义(即我不能重命名类)。此外,我无法修改 fun
的签名,而且我不想在 fun
中使用预处理器指令。有没有一种方法可以使用元编程来编译和工作,而不管包含 Obj
的哪个定义:
void fun(const Obj& obj)
{
impl(obj); // executes some code if obj.x is an object
// executes some other code if obj.x is an array
}
?有没有办法在没有 C++11 功能的情况下做到这一点?
最佳答案
您可以根据decltype(obj.x)
选择模板的特化:
template<typename T>
void impl(const Obj&);
template<>
void impl<Type>(const Obj&) {}
template<>
void imp<Type[42]>(const Obj&) {}
void fun(const Obj& obj)
{
impl<decltype(obj.x)>(obj);
}
可能的 C++03 方法是一个成员检测器特征类,它检查是否存在 Type Obj::x
。这一次,impl
的模板参数将是 bool
,因此您可以简单地传递检查结果:
template<typename C>
struct has_Type_x {
template<typename U, U>
struct Check;
typedef char(&yes)[1];
typedef char(&no)[2];
template<typename> static no test(...);
template<typename U> static yes test(Check<Type U::*, &U::x>*);
static const bool value = sizeof(test<C>(0)) == sizeof(yes);
};
template<bool> void impl(const Obj&);
template<>
void impl<true>(const Obj&) {}
template<>
void impl<false>(const Obj&) {
std::cout << "arr";
}
void fun(const Obj& obj)
{
impl< has_int_x<Obj>::value >(obj);
}
关于c++ - 为具有对象或对象数组作为成员的类运行不同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954558/