c++ - 如何使用boost is_class 来判断一个对象是否是一个类?

标签 c++ boost

对于下面的代码:

template<class _InIt,
class _Ty,
class _Fn2> inline
_Ty accumulateSimplePtr(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)
{   // return sum of _Val and all in [_First, _Last), using _Func
for (; _First != _Last; ++_First)
{
    if(is_class<std::iterator_traits<_InIt>::value_type>::value)
        _Val = _Func(_Val, (*_First)());
    else
        _Val=_Func(_Val, *_First);
}
            return (_Val);
}

我如何判断 _InIt 是指向类/结构还是指向诸如 double 之类的 pod 的交互器?

如果它指向一个 double ,我想使用 *_First 来获取数据,如果它指向一个类,我会使用 (*_First)() 来获取实际数据(假设该类有一个重载的 operator()。

我尝试了上面的方法,但是它无法通过行“_Val=_Func(_Val, *_First);”编译,说 MyObj 不能转换为 double。

最佳答案

#include <iostream>
#include <type_traits>
#include <vector>

class A
{
public:
    int a;
    int b;
};

template<typename T>
struct IsClass
{
    enum { Yes = std::is_class<T>::value };
    enum { No = !Yes };
};

int main(int argc, char* argv[])
{
    std::vector<int> v1;
    std::vector<A> v2;
    auto it1 = v1.begin();
    auto it2 = v2.begin();

    std::cout << IsClass<std::decay<decltype(it1)>::type::value_type>::Yes << std::endl;
    std::cout << IsClass<std::decay<decltype(it2)>::type::value_type>::Yes << std::endl;

    std::cin.get();
    return 0;
}

output对于这些行是 0(假,对于 int vector )和 1(真,对于 A vector )。

关于c++ - 如何使用boost is_class 来判断一个对象是否是一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17499208/

相关文章:

c++ - 如何确保特定类只能创建另一个类的实例?

c++ - 列出 vector 元素时程序崩溃 (C++)

c++ - 多操作系统编译上的 boost::shared_ptr 与 std::tr1::shared_ptr

c++ - 如何在 Visual Studio 2010 中设置单独的 Boost 测试项目

c++ - 如何使用 boost ptree 删除 xml 属性?

android - 如何使用 Windows 使用 NDK r18b 为 Android 编译 boost 1.68.0

c++ - 无法在 C++ 中创建文本文件

c++ - CUDA 设备代码支持哪些真正的 C++ 语言结构?

c++ - 优化级别为 -O2 的 boost::any_range 导致崩溃

c++ - 如何在 ubuntu 20.04 中预编译 <bits/stdc++.h> 头文件?