由于C++11引入了移动语义,我想知道该函数是否可以同时返回值和操作状态。实际上,实施起来并不困难,但我即将开始一个新的大型项目,不知道我是应该这样做,还是使用一些老式的东西。所以我很好奇你的意见。
请考虑以下符号:
class File
{
FILE *file = nullptr;
public:
Result<void> open(const char *fileName);
Result<void> close();
Result<size_t> size();
Result<void> seek(size_t newPosition);
Result<size_t> position();
Result<char> readCharacter();
};
现在让我们分析一个使用示例:
Result<void> processFile(const char *fileName)
{
File file;
auto result = file.open(fileName);
if (!result.isSuccess())
return result;
auto fileSize = file.size();
if (!fileSize.isSuccess())
return fileSize;
for (size_t i = 0; i < fileSize; i++) {
auto character = file.readCharacter();
if (!character.isSuccess())
return character;
if (character < 'a' || character > 'z')
return Error::invalidData;
// processfileCharacter(character);
}
return Error::success;
}
如您所见,错误管理变得非常简单。此外,当我只编写头代码时,启用优化后,GCC和MSVC都会生成非常优化的代码。我非常喜欢这个符号,没有看到任何严重的缺点。但我很想听听你的意见。
实施
如果您想测试它,请欣赏代码:
enum class Error: int
{
success,
unknown,
invalidData
// ...
};
结果类别:
template <typename Type = void>
class Result
{
Error error = Error::success;
Type data;
public:
Result() = default;
Result(Result &&result) = default;
Result(const Result &result) = default;
template <typename OtherType> Result(const Result<OtherType> &result) : error(result.error) {}
Result & operator =(Result &&result) = default;
Result & operator =(const Result &result) = default;
template <typename OtherType> Result & operator =(const Result<OtherType> &result) { error = result; return *this; }
Result(const Type &data) : data(data) {}
Result(Type &&data) : data(std::move(data)) {}
Result(const Error &error) : error(error) {}
Result(Error &&error) : error(std::move(error)) {}
operator Type& () { return data; }
operator const Type& () const { return data; }
operator const Error() const { return error; }
bool isSuccess() const { return error == Error::success; }
};
void专用化:
template <>
class Result<void>
{
Error error = Error::success;
public:
Result() = default;
Result(Result &&result) = default;
Result(const Result &result) = default;
template <typename OtherType> Result(const Result<OtherType> &result) : error(result.error) {}
Result & operator =(Result &&result) = default;
Result & operator =(const Result &result) = default;
template <typename OtherType> Result & operator =(const Result<OtherType> &result) { error = result; return *this; }
Result(const Error &error) : error(error) {}
Result(Error &&error) : error(std::move(error)) {}
operator const Error() const { return error; }
bool isSuccess() const { return error == Error::success; }
};