在 boost::type_traits::条件中使用类型特征的编译错误

Compilation error with Type Traits in boost::type_traits::conditional

本文关键字:类型 特征 编译 错误 type boost traits 条件      更新时间:2023-10-16

我在使用 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&) [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::condition 的问题,因为它似乎没有被正确评估。我的代码中是否存在问题,或者可以使用替代 boost::condition 的替代方法来具有此功能?

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

您需要使用 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;