【问题标题】:Compilation error with Type Traits in boost::type_traits::conditionalboost::type_traits::conditional 中类型特征的编译错误
【发布时间】:2012-10-02 14:56:04
【问题描述】:

我在使用 boost 中的 type_traits 的某些代码中遇到问题。 这是代码中相当复杂的部分,但我可以隔离导致编译错误的部分:

template<const size_t maxLen>
class MyString {
public:
    typedef boost::conditional<(maxLen > 0), char[maxLen+1], std::string> ObjExternal;
};

template <class T>
class APIBase {
public:
    typedef T obj_type;
    typedef typename T::ObjExternal return_type;
};

template <class T>
int edit(const T& field, const typename T::return_type& value)
{
    return 0;
}

int myFunction()
{
    APIBase<MyString<10> > b;
    char c[11];
    return edit(b, c);
}

这会产生以下错误:

test.cpp:在函数“int myFunction()”中: tes.cpp:109: 错误: 没有匹配函数调用‘edit(APIBase >&, char [11])’ tes.cpp:100:注意:候选人是:int edit(const T&, const typename T::return_type&) [with T = APIBase >]

但是,如果我用代码更改行

char c[11];

通过

MyString<10>::ObjExternal c;

它有效。同样,如果我改为更改行

typedef boost::conditional<(maxLen > 0), char[maxLen+1], std::string> ObjExternal;

通过

typedef char ObjExternal[maxLen+1];

它也有效。我认为这是 boost::conditional 的问题,因为它似乎没有被正确评估。我的代码是否有问题,或者可以使用替代方法代替 boost::conditional 来获得此功能?

我正在考虑使用第二个选项,但后来我无法将 maxLen 用作 0。

【问题讨论】:

    标签: c++ templates boost conditional typetraits


    【解决方案1】:

    您需要使用conditional提供的成员typedef type,而不是条件类型本身。

    变化:

    typedef boost::conditional<(maxLen > 0),
                               char[maxLen+1],
                               std::string> ObjExternal;
    

    到:

    typedef typename boost::conditional<(maxLen > 0),
                                        char[maxLen+1],
                                        std::string>::type ObjExternal;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多