c++ - boost::type_traits::conditional 中类型特征的编译错误

标签 c++ templates boost conditional-statements typetraits

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

最佳答案

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

关于c++ - boost::type_traits::conditional 中类型特征的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848109/

相关文章:

c++ - 缠绕式类型转换

c++ - Boost Spirit Qi,我有一个解析器,我想将其映射到结构 "dynamically"(意味着参数的顺序不固定)

c++ - 在 3 元素映射 C++ 中添加新项目并使用时间键搜索

c++ - boost::ptr_vector 成员函数列表

c# - 如何在 C# 中为不同的类传递函数指针委托(delegate)

C++模板函数错误: template-id does not match any template declaration

c++ - 编译时类型检查 C++

C++ 用指针反转字符串中单词的顺序

c++ - 在 C++ 构造函数中初始化数组

c++ - 使用 boost 库编写多线程程序时出错