c++ - 为具有对象或对象数组作为成员的类运行不同的代码

标签 c++ templates template-meta-programming

我有一个以对象为参数的方法

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/

相关文章:

c++ - 错误 1 ​​错误 C2665 : 'DoublyListIterator<Datatype>::DoublyListIterator' : none of the 2 overloads could convert all the argument types

c++ - C++11 中的 decltype(auto) - 推导返回类型

c++ - 关于模板的编译器警告

c++ - 专门化成员函数时出现 "too many template-parameter-lists"错误

c++ - 为什么这有效(Templates,SFINAE)。 C++

C++ vector 存储基类指针

javascript - 这是在 Angular 上破坏模板缓存的好方法吗?

c++ - 如何从双参数模板创建单参数模板以用作基类模板模板参数

c++ - 优化switch的模板替换

c++ - 检查模板参数是否在同质参数包中出现两次以上