Adding a minimal implementation of std::optional. (#783)

We're using C++11, which doesn't have std::optional. We need a few
features of std::optional for improved GPS support. These are
implemented here.
master
Susanne Pielawa 2018-01-05 11:27:21 +01:00 committed by Wally B. Feed
parent 58d94aaa68
commit 63a80c9340
2 changed files with 104 additions and 0 deletions

View File

@ -0,0 +1,55 @@
/*
* Copyright 2017 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_COMMON_OPTIONAL_H_
#define CARTOGRAPHER_COMMON_OPTIONAL_H_
#include <memory>
#include "cartographer/common/make_unique.h"
#include "glog/logging.h"
namespace cartographer {
namespace common {
template <class T>
class optional {
public:
optional() {}
optional(const optional& other) {
if (other.has_value()) {
value_ = common::make_unique<T>(other.value());
}
}
explicit optional(const T& value) { value_ = common::make_unique<T>(value); }
bool has_value() const { return value_ != nullptr; }
const T& value() const {
CHECK(value_ != nullptr);
return *value_;
}
private:
std::unique_ptr<T> value_;
};
} // namespace common
} // namespace cartographer
#endif // CARTOGRAPHER_COMMON_OPTIONAL_H_

View File

@ -0,0 +1,49 @@
/*
* Copyright 2017 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cartographer/common/optional.h"
#include "gtest/gtest.h"
namespace cartographer {
namespace common {
namespace {
TEST(OptionalTest, CreateDisengagedObject) {
const optional<int> o;
EXPECT_FALSE(o.has_value());
const optional<float> x;
EXPECT_FALSE(x.has_value());
}
TEST(OptionalTest, CreateWithValue) {
const optional<int> a(5);
EXPECT_TRUE(a.has_value());
EXPECT_EQ(5, a.value());
}
TEST(OptionalTest, CreateFromOtherOptional) {
const optional<int> a(5);
const optional<int> b = a;
EXPECT_TRUE(a.has_value());
EXPECT_TRUE(b.has_value());
EXPECT_EQ(5, a.value());
EXPECT_EQ(5, b.value());
}
} // namespace
} // namespace common
} // namespace cartographer