当前位置: 首页>>代码示例>>C++>>正文


C++ optional::get_value_or方法代码示例

本文整理汇总了C++中boost::optional::get_value_or方法的典型用法代码示例。如果您正苦于以下问题:C++ optional::get_value_or方法的具体用法?C++ optional::get_value_or怎么用?C++ optional::get_value_or使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在boost::optional的用法示例。


在下文中一共展示了optional::get_value_or方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: logic_error

    ServerImpl::ServerImpl(connection::ConnectionPtr const &conn,
                           boost::optional<std::string> const &host,
                           boost::optional<int> const &port)
        : m_conn(conn), m_ctx(make_shared<pluginhost::RegistrationContext>()),
          m_host(host.get_value_or("localhost")),
          m_port(port.get_value_or(util::UseDefaultPort)),
          m_log(util::log::make_logger(util::log::OSVR_SERVER_LOG)) {
        if (!m_conn) {
            throw std::logic_error(
                "Can't pass a null ConnectionPtr into Server constructor!");
        }
        osvr::connection::Connection::storeConnection(*m_ctx, m_conn);

        // Get the underlying VRPN connection, and make sure it's OK.
        auto vrpnConn = getVRPNConnection(m_conn);

        if (!(vrpnConn->doing_okay())) {
            throw ServerCreationFailure();
        }

        // Set up system device/system component
        m_systemDevice = common::createServerDevice(
            common::SystemComponent::deviceName(), vrpnConn);

        m_systemComponent =
            m_systemDevice->addComponent(common::SystemComponent::create());
        m_systemComponent->registerClientRouteUpdateHandler(
            &ServerImpl::m_handleUpdatedRoute, this);

        // Things to do when we get a new incoming connection
        // No longer doing hardware detect unconditionally here - see
        // triggerHardwareDetect()
        m_commonComponent =
            m_systemDevice->addComponent(common::CommonComponent::create());
        m_commonComponent->registerPingHandler([&] { m_queueTreeSend(); });

        // Set up the default display descriptor.
        m_tree.getNodeByPath("/display").value() =
            common::elements::StringElement(util::makeString(display_json));
        // Deal with updated device descriptors.
        m_conn->registerDescriptorHandler([&] { m_handleDeviceDescriptors(); });

        // Set up handlers to enter/exit idle sleep mode.
        // Can't do this with the nice wrappers on the CommonComponent of the
        // system device, I suppose since people aren't really connecting to
        // that device.
        vrpnConn->register_handler(
            vrpnConn->register_message_type(vrpn_got_first_connection),
            &ServerImpl::m_exitIdle, this);
        vrpnConn->register_handler(
            vrpnConn->register_message_type(vrpn_dropped_last_connection),
            &ServerImpl::m_enterIdle, this);
    }
开发者ID:DINKIN,项目名称:OSVR-Core,代码行数:53,代码来源:ServerImpl.cpp

示例2: client

StatusWith<Shard::QueryResponse> ShardLocal::_exhaustiveFindOnConfig(
    OperationContext* txn,
    const ReadPreferenceSetting& readPref,
    const repl::ReadConcernLevel& readConcernLevel,
    const NamespaceString& nss,
    const BSONObj& query,
    const BSONObj& sort,
    boost::optional<long long> limit) {
    auto replCoord = repl::ReplicationCoordinator::get(txn);

    if (readConcernLevel == repl::ReadConcernLevel::kMajorityReadConcern) {
        // Set up operation context with majority read snapshot so correct optime can be retrieved.
        Status status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();

        // Wait for any writes performed by this ShardLocal instance to be committed and visible.
        Status readConcernStatus = replCoord->waitUntilOpTimeForRead(
            txn, repl::ReadConcernArgs{_getLastOpTime(), readConcernLevel});
        if (!readConcernStatus.isOK()) {
            return readConcernStatus;
        }

        // Inform the storage engine to read from the committed snapshot for the rest of this
        // operation.
        status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();
        if (!status.isOK()) {
            return status;
        }
    } else {
        invariant(readConcernLevel == repl::ReadConcernLevel::kLocalReadConcern);
    }

    DBDirectClient client(txn);
    Query fullQuery(query);
    if (!sort.isEmpty()) {
        fullQuery.sort(sort);
    }
    fullQuery.readPref(readPref.pref, BSONArray());

    try {
        std::unique_ptr<DBClientCursor> cursor =
            client.query(nss.ns().c_str(), fullQuery, limit.get_value_or(0));

        if (!cursor) {
            return {ErrorCodes::OperationFailed,
                    str::stream() << "Failed to establish a cursor for reading " << nss.ns()
                                  << " from local storage"};
        }

        std::vector<BSONObj> documentVector;
        while (cursor->more()) {
            BSONObj document = cursor->nextSafe().getOwned();
            documentVector.push_back(std::move(document));
        }

        return Shard::QueryResponse{std::move(documentVector),
                                    replCoord->getCurrentCommittedSnapshotOpTime()};
    } catch (const DBException& ex) {
        return ex.toStatus();
    }
}
开发者ID:Machyne,项目名称:mongo,代码行数:60,代码来源:shard_local.cpp

示例3: last_index_of

int binary::last_index_of(
  value byte_, boost::optional<int> start_, boost::optional<int> stop_)
{
  int byte = get_byte(byte_);
  int start = start_.get_value_or(0);
  if (start < 0)
    start = 0;
  int stop = stop_.get_value_or(get_length() - 1);
  if (std::size_t(stop) >= get_length())
    stop = get_length() - 1;

  for (; start <= stop; --stop)
    if (v_data[stop] == byte)
      return stop;
  return -1;
}
开发者ID:Flusspferd,项目名称:flusspferd,代码行数:16,代码来源:binary.cpp

示例4: create

void file::create(char const *name, boost::optional<int> mode) {
  security &sec = security::get();

  if (!sec.check_path(name, security::CREATE))
    throw exception("Could not create file (security)");

  if (creat(name, mode.get_value_or(0666)) < 0)
    throw exception("Could not create file");
}
开发者ID:the-kenny,项目名称:flusspferd,代码行数:9,代码来源:file.cpp

示例5:

 VrpnBasedConnection::VrpnBasedConnection(
     boost::optional<std::string const &> iface, boost::optional<int> port) {
     int myPort = port.get_value_or(0);
     if (iface && !(iface->empty())) {
         m_initConnection(iface->c_str(), myPort);
     } else {
         m_initConnection(nullptr, myPort);
     }
 }
开发者ID:OSVR,项目名称:OSVR-Core,代码行数:9,代码来源:VrpnBasedConnection.cpp

示例6: client

StatusWith<Shard::QueryResponse> ShardLocal::_exhaustiveFindOnConfig(
    OperationContext* txn,
    const ReadPreferenceSetting& readPref,
    const NamespaceString& nss,
    const BSONObj& query,
    const BSONObj& sort,
    boost::optional<long long> limit) {
    // Set up operation context with majority read snapshot so correct optime can be retrieved.
    Status status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();
    auto replCoord = repl::ReplicationCoordinator::get(txn);

    // Ensure timeout is set on the txn so we don't wait forever for the snapshot.
    // TODO (SERVER-18277): Remove this
    CurOp::get(txn)->ensureStarted();

    // Wait until a snapshot is available.
    while (status == ErrorCodes::ReadConcernMajorityNotAvailableYet) {
        LOG(1) << "Waiting for ReadFromMajorityCommittedSnapshot to become available";
        replCoord->waitUntilSnapshotCommitted(txn, SnapshotName::min());
        status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();
    }

    if (!status.isOK()) {
        return status;
    }

    DBDirectClient client(txn);
    Query fullQuery(query);
    if (!sort.isEmpty()) {
        fullQuery.sort(sort);
    }
    fullQuery.readPref(readPref.pref, BSONArray());

    try {
        std::unique_ptr<DBClientCursor> cursor =
            client.query(nss.ns().c_str(), fullQuery, limit.get_value_or(0));

        if (!cursor) {
            return {ErrorCodes::OperationFailed,
                    str::stream() << "Failed to establish a cursor for reading " << nss.ns()
                                  << " from local storage"};
        }

        std::vector<BSONObj> documentVector;
        while (cursor->more()) {
            BSONObj document = cursor->nextSafe().getOwned();
            documentVector.push_back(std::move(document));
        }

        return Shard::QueryResponse{std::move(documentVector),
                                    replCoord->getCurrentCommittedSnapshotOpTime()};
    } catch (const DBException& ex) {
        return ex.toStatus();
    }
}
开发者ID:MPOWER4RU,项目名称:mongo,代码行数:55,代码来源:shard_local.cpp

示例7: substring

object byte_string::substring(int first, boost::optional<int> last_) {
  if (first < 0)
    first = 0;
  if (std::size_t(first) > get_length())
    first = get_length();
  int last = last_.get_value_or(get_length());
  if (last < 0)
    last = 0;
  if (std::size_t(last) > get_length())
    last = get_length();
  if (last < first)
    std::swap(first, last);
  return create(&get_data()[first], last - first);
}
开发者ID:Flusspferd,项目名称:flusspferd,代码行数:14,代码来源:binary.cpp

示例8:

std::pair<std::size_t, std::size_t>
binary::length_range(int start, boost::optional<int> length_) {
  if (start < 0)
    start += get_length();
  if (start < 0)
    start = 0;
  if (std::size_t(start) >= get_length())
    start = get_length();
  int length = length_.get_value_or(get_length() - start);
  if (length < 0)
    length = 0;
  if (std::size_t(length) > get_length() - start)
    length = get_length() - start;
  return std::pair<std::size_t, std::size_t>(start, start + length);
}
开发者ID:Flusspferd,项目名称:flusspferd,代码行数:15,代码来源:binary.cpp

示例9: process

void Remote::process(const Coordinate & pos, boost::optional<floatCoordinate> normal) {
    //distance vector
    floatCoordinate deltaPos = pos - state->viewerState->currentPosition;
    const float jumpThreshold = 0.5f * Dataset::current().cubeEdgeLength * state->M * Dataset::current().magnification;//approximately inside sc
    if (deltaPos.length() > jumpThreshold) {
        state->viewer->setPosition(pos);
    } else if (pos != state->viewerState->currentPosition) {
        rotate = normal.is_initialized();
        normal = normal.get_value_or({});
        targetPos = pos;
        recenteringOffset = pos - state->viewerState->currentPosition;
        elapsed.restart();
        timer.start(ms);
        state->viewer->userMoveClear();
        remoteWalk();
    }
}
开发者ID:knossos-project,项目名称:knossos,代码行数:17,代码来源:remote.cpp

示例10: installNewBattleInterface

void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback)
{
	boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
	PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);

	if(!color)
		privilegedBattleEventReceivers.push_back(battleInterface);

	battleints[colorUsed] = battleInterface;

	if(needCallback)
	{
		logGlobal->trace("\tInitializing the battle interface for player %s", *color);
		auto cbc = std::make_shared<CBattleCallback>(color, this);
		battleCallbacks[colorUsed] = cbc;
		battleInterface->init(cbc);
	}
}
开发者ID:vcmi,项目名称:vcmi,代码行数:18,代码来源:Client.cpp

示例11: installNewPlayerInterface

void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color, bool battlecb)
{
	boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
	PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);

	if(!color)
		privilegedGameEventReceivers.push_back(gameInterface);

	playerint[colorUsed] = gameInterface;

	logGlobal->trace("\tInitializing the interface for player %s", colorUsed);
	auto cb = std::make_shared<CCallback>(gs, color, this);
	callbacks[colorUsed] = cb;
	battleCallbacks[colorUsed] = cb;
	gameInterface->init(cb);

	installNewBattleInterface(gameInterface, color, battlecb);
}
开发者ID:vcmi,项目名称:vcmi,代码行数:18,代码来源:Client.cpp

示例12: fullQuery

StatusWith<std::vector<ChunkType>> readShardChunks(OperationContext* opCtx,
                                                   const NamespaceString& nss,
                                                   const BSONObj& query,
                                                   const BSONObj& sort,
                                                   boost::optional<long long> limit,
                                                   const OID& epoch) {
    // Query to retrieve the chunks.
    Query fullQuery(query);
    fullQuery.sort(sort);

    try {
        DBDirectClient client(opCtx);

        std::string chunkMetadataNs = ChunkType::ShardNSPrefix + nss.ns();
        std::unique_ptr<DBClientCursor> cursor =
            client.query(chunkMetadataNs, fullQuery, limit.get_value_or(0));

        if (!cursor) {
            return {ErrorCodes::OperationFailed,
                    str::stream() << "Failed to establish a cursor for reading " << chunkMetadataNs
                                  << " from local storage"};
        }

        std::vector<ChunkType> chunks;
        while (cursor->more()) {
            BSONObj document = cursor->nextSafe().getOwned();
            auto statusWithChunk = ChunkType::fromShardBSON(document, epoch);
            if (!statusWithChunk.isOK()) {
                return {statusWithChunk.getStatus().code(),
                        str::stream() << "Failed to parse chunk '" << document.toString()
                                      << "' due to "
                                      << statusWithChunk.getStatus().reason()};
            }
            chunks.push_back(std::move(statusWithChunk.getValue()));
        }

        return chunks;
    } catch (const DBException& ex) {
        return ex.toStatus();
    }
}
开发者ID:bjori,项目名称:mongo,代码行数:41,代码来源:shard_metadata_util.cpp


注:本文中的boost::optional::get_value_or方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。