Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.


// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at
// See:

#include <boost/contract.hpp>
#include <boost/optional.hpp>
#include <vector>
#include <cassert>

template<unsigned Index, typename T>
T& get(std::vector<T>& vect) {
    boost::optional<T&> result; // Result not initialized here...
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(Index < vect.size());
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(*result == vect[Index]);
    // Function body (executed after preconditions checked).
    return *(result = vect[Index]); // ...result initialized here instead.

int main() {
    std::vector<int> v;
    int& x = get<1>(v);
    assert(x == 456);
    x = -456;
    assert(v[1] == -456);
    return 0;