/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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. */
folly/DynamicConverter.h
When dynamic objects contain data of a known type, it is sometimes
useful to have its well-typed representation. A broad set of
type-conversions are contained in DynamicConverter.h
, and
facilitate the transformation of dynamic objects into their well-typed
format.
Simply pass a dynamic into a templated convertTo:
= { { 1, 2, 3 }, { 4, 5 } }; // a vector of vector of int
dynamic d auto vvi = convertTo<fbvector<fbvector<int>>>(d);
convertTo naturally supports conversions to
NOTE:
convertTo
Additionally, convertTo
If Type meets the container criteria, then it will be constructed by calling its InputIterator constructor.
If you want to use convertTo to convert dynamics into your own custom class, then all you have to do is provide a template specialization of DynamicConverter with the static method convert. Make sure you put it in namespace folly.
Example:
struct Token {
int kind_;
lexeme_;
fbstring
explicit Token(int kind, const fbstring& lexeme)
: kind_(kind), lexeme_(lexeme) {}
};
namespace folly {
template <> struct DynamicConverter<Token> {
static Token convert(const dynamic& d) {
int k = convertTo<int>(d["KIND"]);
= convertTo<fbstring>(d["LEXEME"]);
fbstring lex return Token(k, lex);
}
};
}