0

我在使用 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。

4

1 回答 1

1

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

改变:

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

到:

typedef typename boost::conditional<(maxLen > 0),
                                    char[maxLen+1],
                                    std::string>::type ObjExternal;
于 2012-10-11T20:50:39.107 回答