gpt4 book ai didi

C++ Template meta-magic, template call-site qualification deduction机制

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:58:59 27 4
gpt4 key购买 nike

我为这个例子的冗长道歉,我从一个项目中设计出来的。注释,第 1 项和第 2 项在以下代码中很重要。

#include <boost/intrusive/set.hpp>

struct x : public boost::intrusive::set_base_hook<>
{
int y;
};

struct finder
{
bool operator()(const int & i, const x & _x) const
{ return i < _x.y;}
bool operator()(const x & _x, const int & i) const
{ return _x.y < i;}
};

class trampoline
{
public:
void bounce() const /* item 1 */
{
/*item 2*/
boost::intrusive::set<x>::iterator it = _set.find(1,finder());
}

boost::intrusive::set<x> _set;
};

int main()
{
trampoline t;
t.bounce();
}

我不能将非 const 迭代器带到我的成员容器(第 2 项),其中范围内的函数是 const,如果我将迭代器切换到 const_iterator 一切正常,或者如果我将封闭函数设为非 const也有效。完全有道理,现在,经过一个小时的逆向工程后,出现以下错误消息的问题:

test.cc: In member function ‘void trampoline::bounce() const’:test.cc:21: error: conversion from ‘boost::intrusive::tree_iterator<boost::intrusive::rbtree_impl<boost::intrusive::setopt<boost::intrusive::detail::base_hook_traits<x, boost::intrusive::rbtree_node_traits<void*, false>, (boost::intrusive::link_mode_type)1u, boost::intrusive::default_tag, 3>, std::less<x>, long unsigned int, true> >, true>’ to non-scalar type ‘boost::intrusive::tree_iterator<boost::intrusive::rbtree_impl<boost::intrusive::setopt<boost::intrusive::detail::base_hook_traits<x, boost::intrusive::rbtree_node_traits<void*, false>, (boost::intrusive::link_mode_type)1u, boost::intrusive::default_tag, 3>, std::less<x>, long unsigned int, true> >, false>’ requested

这最终让我想到了以下模板定义 (/include/boost/intrusive/detail/tree_node.hpp +72):

/////////////////////////////////////////////////////////////////////////////
// //
// Implementation of the tree iterator //
// //
/////////////////////////////////////////////////////////////////////////////

// tree_iterator provides some basic functions for a
// node oriented bidirectional iterator:
template<class Container, bool IsConst>

够了所以说我很快就解决了问题......

该模板是如何从封闭函数的调用点传递 IsConst 的?我的大脑准备爆炸(据我所知,这很简单,但我很困惑)。详细解释并逐步实现以解释机制会很有帮助。

我有一个类似的问题here类似于 C++ 模板机制的类型推导/别名。引用是值得赞赏的,但它们需要被仔细考虑到知识中:D。如果您有耐心回答这个问题,您可能想尝试就另一个问题展开讨论。

最佳答案

boost::intrusive::set 的 find() 成员函数不会有一个 const 和非常量重载吗?我的意思是,我会这样做:

template <typename T /*...*/ >
class set {
//...
public:
template <bool isConst>
class iterator {
//....
};
iterator<true> find(/*..*/) const; //notice the const
iterator<false> find(/*..*/); //notice no const
};

这真的不是元编程魔术,只是很好的老式常量正确性。

关于C++ Template meta-magic, template call-site qualification deduction机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5329033/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com