Creating new types in C++ - c++

Using typedef in C++ creates an alias for a type.
So:
typedef double Length;
typedef double Mass;
creates two aliases which can be intermixed. In other words we can pass a value of type Mass to a function that expects a value of type Length.
Is there a lightweight way of creating new types? I would like them to be double underneath but be "different" so that one can't be used in place of another.
I would prefer something lighter than creating a new class or struct. Also, I am aware of the dimensions lib in boost. This is more complex and does a lot more than I need.

BOOST_STRONG_TYPEDEF seems to be designed exactly for what you're looking for. I believe it does it's magic by creating a class and overloading the operators to make it behave like a builtin type, but I've not looked at it's implementation.

While BOOST_STRONG_TYPEDEF is a pretty simple solution, if you're mixing lengths and masses into more complicated units (e.g. in the physical sciences) then you might want to use Boost.Units.

One other possible answer in C++11 is to use enum class : type. This will allow you to do what you want but it has its own downsides. For example you would have to overload a lot of operators.
#include <iostream>
#include <string>
enum class A : int;
enum class B : int;
std::ostream& operator<<(std::ostream& os, const A& t){
os << static_cast<int>(t);
return os;
}
std::ostream& operator<<(std::ostream& os, const B& t){
os << static_cast<int>(t);
return os;
}
int test(A t){
std::cout << "A " << t << std::endl;
return 0;
}
int test(B t){
std::cout << "B " << t << std::endl;
return 0;
}
int main(){
A a{static_cast<A>(42)};
B b{static_cast<B>(0)};
test(a);
test(b);
}
This would give the output of:
A 42
B 0
Or you could just get the integer part like this
template<class T>
int GetInt(T t)
{
return static_cast<int>(t);
}
std::cout << "B " << GetInt(t) << std::endl;

If the Metaclasses proposal (p7070) goes through (right now it's still at revision0), then we shall be able to create strong typedefs using an empty metaclass. Proposed syntax:
$class strong_typedef { };
using Length = $double.as(strong_typedef);
using Mass = $double.as(strong_typedef);
Earliest we might see this would be C++20

Related

C++: Non-typed Function Pointer

How can I save a pointer to a function without save its return type?
For example:
int GetInt() { return 5; }
string GetStr() { return "abc"; }
FunctionPointerClass GetAny;
int main()
{
GetAny = &GetInt;
auto var = GetAny();
GetAny = &GetStr;
auto var2 = GetAny();
cout << var << '\n' << var2;
}
Edit
A simple way to do this is use variant<> (thanks #sehe), like this:
#include <boost/variant.hpp>
#include <string>
#include <iostream>
#include <functional>
int GetInt() { return 5; }
std::string GetStr() { return "abc"; }
int main()
{
std::function<boost::variant<int, std::string>()> Get;
Get = &GetInt;
std::cout << Get() << '\n';
Get = &GetStr;
std::cout << Get() << '\n';
}
But, it not too applicable for my project: a non-typed class. To use it, I will need stack all the used return types, to put it in template of variant<>. Like this:
class Var {
private:
void* _val;
template <typename T>
T& _Get() const {
return *((T*)_val);
}
// Static stack variable HERE
public:
val() {}
template <typename T>
val(T val) {
Set(val);
}
~val() {
if(_val != nullptr) delete _val;
}
std::function<boost::variant</*Stack*/>()> Get;
template <typename T>
void Set(T val) {
if(_val != nullptr) delete _val;
_val = new T(val);
Get = &_Get<T>;
// TODO Add 'T' to Stack
}
};
How can I do this?
Not exactly.
You can of course make it a function to print the value.
Or you can use std::variant/boost::variant to return either type.
Other techniques, like Type Erasure might also apply.
I flesh the last two of the approaches here:
Using variant<>
Live On Coliru
#include <boost/variant.hpp>
#include <string>
#include <iostream>
#include <functional>
int GetInt() { return 5; }
std::string GetStr() { return "abc"; }
int main()
{
std::function<boost::variant<int, std::string>()> Get;
Get = &GetInt;
std::cout << Get() << '\n';
Get = &GetStr;
std::cout << Get() << '\n';
}
Prints
5
abc
Using type erasure
A related technique is type erasure, where you define a "concept" with supported operations (in this case, output streaming) and you hide it behind a polymorphic interface. E.g:
struct Printable {
template <typename T> Printable(T v) : _stored(new concrete<T>(v)) { }
friend std::ostream& operator<<(std::ostream& os, Printable const& p) {
return p._stored->print(os);
}
private:
struct interface {
virtual std::ostream& print(std::ostream& os) const = 0;
virtual ~interface() = default;
};
template <typename T>
struct concrete : interface {
concrete(T v) : v(v) {}
virtual std::ostream& print(std::ostream& os) const override {
return os << v;
}
T v;
};
std::unique_ptr<interface> _stored;
};
In that case you can make the whole program:
Live On Coliru
int GetInt() { return 5; }
std::string GetStr() { return "abc"; }
int main()
{
std::function<Printable()> Get;
Get = &GetInt;
std::cout << Get() << '\n';
Get = &GetStr;
std::cout << Get() << '\n';
}
I was going to write this as a comment, and it's not REALLY an answer, but it's a lengthy discussion on the subject of "return different types from the a function with the same name".
C++ doesn't take return type into concideration for overloading functions. In other words, std::string GetAny() and int GetAny() are considered as duplicates of the same function, because they only differ in return type. That's a restriction in the language definition, and you have to work around this restriction by "doing something other than return two different types".
As discussed in another answer, one solution is boost::variant, which is basically a way to define a class that can have multiple different types inside it, which has a type of "tag" to determine what it really contains, and various other clever stuff related to that. Makes it very neat in many ways.
However, it is only really useful for certain classes of problems. In many cases, your code still needs to understand what the data-type is, and having a function that may return a string, an integer or any other "random" data type isn't meaningful. Yes, it's handy to be able to define function pointers that return "any" type - but only in so far as you can have a table of the functions. Your code will not really work well if you do:
std::string s;
s += GetAny(); // Happens to be returning `int` in this call.
Just as bad:
int x = GetAny(); // Returning a string...
So, whilst you can write code that may return "any type", it's hard to make use of such a function without knowing what it returns. I've been programming professionally for over 30 years, and I have used function pointers for many things. So far, I've managed to not need to use this more than a handful times, and every time, it's been some form of solution similar to boost::variant (essentially returning a data-structure, where one field is describing the data-type itself). The two cases I can think of where I have used this are in my Lisp interpreter and my Basic intrepreter. They need a "variable type" that have the ability to hold various types of objects (integer, float, string, list [only in Lisp]). In my Pascal compiler, I do have a proper type system, so it doesn't need to have multiple types returned from a single function (or function pointer). I'd say "it smells funny" when this type of situation happens, and you should probably think about what it is you're trying to solve, and if this is really the right solution.

Using enum class with std::bitset

First of all I want a normal enumeration instead of a bit-based enumeration, because the amount of different enums will be beyond any integral type. I also want to take advantage of the type safety of C++11 enum class. To do so, the natural choice would be std::bitset, however I have no idea how to bind those two together.
A custom bitset would be needed? How to go around the implementation of such a class?
Since enum classes are wrappers for enums, you can cast them to underlying type. And using some private inheritance you can selectively import some functionalities from C++ stdlib classes without worrying about Liskov's principle. Composition resulted in clearer code. Using these functionalities, we can wrap std::bitset. Following code contains only subset of functionalites, but it can be expanded further.
There's a problem with max value - that you can't get maximum value of enum class (or am I wrong?). So I added EnumTraits. Now users are required to specialize EnumTraits with const value max equal to the max value of enum before class can be used.
#include <bitset>
#include <type_traits>
template<typename T>
struct EnumTraits;
template<typename T>
class EnumClassBitset
{
private:
std::bitset<static_cast<typename std::underlying_type<T>::type>(EnumTraits<T>::max)> c;
typename std::underlying_type<T>::type get_value(T v) const
{
return static_cast<typename std::underlying_type<T>::type>(v);
}
public:
EnumClassBitset() : c()
{
}
bool test(T pos) const
{
return c.test(get_value(pos));
}
EnumClassBitset& reset(T pos)
{
c.reset(get_value(pos));
return *this;
}
EnumClassBitset& flip(T pos)
{
c.flip(get_value(pos));
return *this;
}
};
enum class BitFlags
{
False,
True,
FileNotFound,
Write,
Read,
MaxVal
};
template<>
struct EnumTraits<BitFlags>
{
static const BitFlags max = BitFlags::MaxVal;
};
#include <iostream>
int main()
{
EnumClassBitset<BitFlags> f;
f.flip(BitFlags::True);
f.flip(BitFlags::FileNotFound);
//f.flip(2); //fails to compile
std::cout << "Is False? " << f.test(BitFlags::False) << "\n";
std::cout << "Is True? " << f.test(BitFlags::True) << "\n";
std::cout << "Is FileNotFound? " << f.test(BitFlags::FileNotFound) << "\n";
std::cout << "Is Write? " << f.test(BitFlags::Write) << "\n";
std::cout << "Is Read? " << f.test(BitFlags::Read) << "\n";
}
Since enums don't have much functionality unfortunately, and what is more, C++11 with enum classes don't improve the situation, some programmers use static map wrapped in a class. Definitely a good read.

How to print boost::any to a stream?

I have a Map std::map<std::string, boost::any>, which comes from the boost::program_options package. Now I would like to print the content of that map:
for(po::variables_map::const_iterator it = vm.begin(); it != vm.end(); ++it) {
std::cerr << it->first << ": " << it->second << std::endl;
}
Unfortunately, that is not possible because boost::any doesn't have an operator<< defined.
What is the easiest way to print that map?
I could define my own output operator for any that automatically tries to cast each any to an int, then double, then string, etc., each time ignoring errors and trying to cast until the cast is successful and I can print as the specified type.
But there should be an easier method in Boost? I'd need something like a reverse lexical_cast...
You could use boost::spirit::hold_any instead. It's defined here:
#include <boost/spirit/home/support/detail/hold_any.hpp>
and is fully compatible with boost::any. This class has two differences if compared to boost::any:
it utilizes the small object optimization idiom and a couple of other optimization tricks, making spirit::hold_any smaller and faster than boost::any
it has the streaming operators (operator<<() and operator>>()) defined, allowing to input and output a spirit::hold_any seemlessly.
The only limitation is that you can't input into an empty spirit::hold_any, but it needs to be holding a (possibly default constructed) instance of the type which is expected from the input.
If you can change boost::any to another type, you can use Boost.TypeErasure. If you ever wanted to create a type that's like any, but only supporting types that support these particular operations at compile time, then this is just for you.
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/mpl/vector.hpp>
#include <random>
#include <iostream>
namespace te = boost::type_erasure;
typedef te::any<boost::mpl::vector<
te::copy_constructible<>,
te::destructible<>,
te::ostreamable<>
>> streamable_any;
int main()
{
streamable_any i(42);
streamable_any d(23.5);
std::mt19937 mt;
streamable_any r(mt);
std::cout << i << "\n" << d << "\n" << r << "\n";
}
Live On Coliru
Unfortunately, with any the only way is to use the type() method to determine what is contained within any, then cast it with any_cast. Obviously you must have RTTI enabled, but you probably already do if you're using any:
for(po::variables_map::const_iterator it = vm.begin(); it != vm.end(); ++it) {
if(typeid(float) == it->second.type()) {
std::cerr << it->first << ": " << any_cast<float>(it->second) << std::endl;
}
else if(typeid(int) == it->second.type()) {
std::cerr << it->first << ": " << any_cast<int>(it->second) << std::endl;
}
...
}
Define some aux function to output to stream:
template<class T>
bool out_to_stream(std::ostream& os, const boost::any& any_value)
{
try {
T v = boost::any_cast<T>(any_value);
os << v;
return true;
} catch(boost:: bad_any_cast& e) {
return false;
}
}
You can define a special formatting for some types
template<>
bool out_to_stream<std::string>(std::ostream& os, const boost::any& any_value)
{
try {
std::string v(std::move(boost::any_cast<std::string>(any_value)));
os << "'" << v << "'";
return true;
} catch(boost:: bad_any_cast& e) {
return false;
}
}
or
template<>
bool out_to_stream<bool>(std::ostream& os, const boost::any& any_value)
{
try {
os << ((boost::any_cast<bool>(any_value))? "yes" : "no");
return true;
} catch(boost:: bad_any_cast& e) {
return false;
}
}
Then define an output operator for boost::any where you list all types you want to try to cast and output
std::ostream& operator<<(std::ostream& os, const boost::any& any_value)
{
//list all types you want to try
if(!out_to_stream<int>(os, any_value))
if(!out_to_stream<double>(os, any_value))
if(!out_to_stream<bool>(os, any_value))
if(!out_to_stream<std::string>(os, any_value))
os<<"{unknown}"; // all cast are failed, an unknown type of any
return os;
}
And then for a value_type:
std::ostream& operator<<(std::ostream& os, const boost::program_options::variable_value& cmdline_val)
{
if(cmdline_val.empty()){
os << "<empty>";
} else {
os<<cmdline_val.value();
if(cmdline_val.defaulted())
os << "(default)";
}
return os;
}
The list of type switches proposed in other answers can be improved with a loop over a type list using Boost MPL (see documentation of mpl::for_each and mpl::vector). The following code defines an operator<< for any boost::any that is given in the type list SupportedTypes and throws an exception otherwise.
#include <stdexcept>
#include <iostream>
#include <string>
#include <cstdint>
#include <boost/any.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
class StreamInserter
{
private:
std::ostream& os_;
const boost::any &v_;
mutable bool has_printed_;
public:
struct UnsupportedType {};
StreamInserter(std::ostream& os, const boost::any &v)
: os_(os), v_(v), has_printed_(false) {}
template <typename T>
void operator()(const T&) const
{
if (!has_printed_ && v_.type() == typeid(T))
{
os_ << boost::any_cast<T>(v_);
has_printed_ = true;
}
}
void operator()(const UnsupportedType&) const
{
if (!has_printed_)
throw std::runtime_error("unsupported type");
}
};
std::ostream& operator<<(std::ostream& os, const boost::any& v)
{
typedef boost::mpl::vector<float, double, int8_t, uint8_t, int16_t, uint16_t,
int32_t, uint32_t, int64_t, uint64_t, std::string, const char*,
StreamInserter::UnsupportedType> SupportedTypes;
StreamInserter si(os, v);
boost::mpl::for_each<SupportedTypes>(si);
return os;
}
int main(int, char**)
{
std::cout << boost::any(42.0) << std::endl;
std::cout << boost::any(42) << std::endl;
std::cout << boost::any(42UL) << std::endl;
std::cout << boost::any("42") << std::endl;
std::cout << boost::any(std::string("42")) << std::endl;
std::cout << boost::any(bool(42)) << std::endl; // throws exception
}
I think you have to cover each possible case of objects you have to print... Or use boost::variant.
EDIT: Sorry, I thought I shall write WHY.
The reason why I think that is because, looking at any source code, it seems to rely on the fact that YOU provide the types when inserting and getting data. When you insert, data is automatically detected by the compiler, so you don't have to specify it. But when you get the data, you shall use any_cast, because you're not sure of the data type you're getting.
If it worked in a different way and data type was sure, I think that would be no need for any_cast :)
Instead, variant have a limited set of possible data types, and this information is somewhat registered, giving you the ability to iterate in a generic way a variant container.
If you need this kind of manipulation - iterating a generic set of values - I think you shall use variant.
Try using xany https://sourceforge.net/projects/extendableany/?source=directory xany class allows to add new methods to any's existing functionality. By the way there is a example in documentation which does exactly what you want.
Rather than re-writing my class to use boost::spirit::hold_any, I created a way to stream boost::any, similar to what manifest suggested, but just in one place.
ostream& operator<<(ostream& _os, const boost::any& _any)
{
// only define simple type conversions
if (_any.type() == typeid(int))
_os << boost::any_cast<int>(_any);
/*any other types you use...*/
}
Rather cumbersome, but it allows me to stream a boost::any variable anywhere in my code.
How about being able to construct a boost::spirit::hold_any from a boost:any?
A little late for this party, but anyone that may be interested can also use std::tuple and a std::for_each-like template that iterates over a tuple.
This is based on the answer from ingomueller.net in this thread.
I had a recent case where I created a property map (reading configuration values, mainly fundamental types, from an XML file and inserting them into an std::unordered_map, where the value type is of type any. For debugging purposes I wanted to be able to print the entire map with its keys and values along with the type of the value.
In that project I am not using Boost at all, I used my own any implementation, but its very similar to boost::any.
The insertion operator basically looks like this:
template <typename TChar>
inline std::basic_ostream<TChar>&
operator<< (std::basic_ostream<TChar>& os, const sl::common::any& v)
{
// Types that we support with sl::common::any.
std::tuple<
float, double, bool,
int8_t, uint8_t,
int16_t, uint16_t,
int32_t, uint32_t,
int64_t, uint64_t,
std::wstring, const wchar_t*,
StreamInserter::UnsupportedType> t;
// Prepare ostream for printing a value of type any
StreamInserter si(os, v);
// Iterate over all types in tuple t. If the last type(UnsupportedType) is
// reached, given v is unsupported.
for_each(t, si);
return os;
}
The for_each template looks like this (C++14):
template <typename Tuple, typename F, std::size_t ...Indices>
constexpr void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
using swallow = int[];
(void)swallow{1,
(f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
};
}
template <typename Tuple, typename F>
constexpr void for_each(Tuple&& tuple, F&& f) {
constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
std::make_index_sequence<N>{});
}
With this just use the StreamInserter class or something similar shown in Ingos answer.
Hope this helps.

Can C++ compiler try different (template T) implementations until it finds one that compiles (for T)?

// First try this:
template <class T> T Read(istream& in) {
T t;
in >> t;
return t;
}
// If there is no operator>>(istream&, T) try this:
template <class T> T Read(istream& in) {
return T (in);
}
// If there is no constructor T(istream&) try this:
template <class T> T Read(istream& in) {
return T::OfStream (in);
}
// now fail.
Can this be implemented?
If not, what are the alternatives?
Are you familiar with the concept of SFINAE? Using this concept, you can include or exclude function templates from the candidate set based on any property of the template arguments. As Alex Martelli said, however, you have to cause this happen in the signature, not the body of the method.
This means you need to be able to make compile-time decisions concerning some property of type T, and use the result of that decision to force the template signature to become illegal, which will exclude that template from the compiler's candidate set without raising a compilation error.
Boost has two libraries that can facilitate this: Boost.TypeTraits, which allows you to ask things like "is T an array?" or "is T a pointer?" or "is T a subclass of U?" at compile time. The result of that query can be used by Boost.EnableIf to exclude a function (or not, as desired).
You may be able to achieve what you are after using a combination of those libraries. If you are using a specific compiler, you may also be able to achieve similar results using compiler-specific extensions (if that's okay with you). For example, using MSVC, you might be able to make use of the __if_exists keyword. Depending on how closely your simple example mirrors what you really want to do, one method may be cleaner than the other.
As mentioned, these are ambiguous. You should look into boosts enable_if or similar, combined with e.g. is_function.
In a standard-compliant C++ implementation, these multiple ambiguous templates should produce an error (ambiguity is defined by signature, not by body). I do not know of any C++ compiler which violates the standard to the extent of allowing this code (that doesn't mean there aren't any crazy-enough compilers, just that I haven't heard of any that are;-).
This cannot be implemented directly as you specified, but there is a workaround. It is possible to define a template conversion operator, and its type parameter can be deduced from the expected target type. Thus, you can introduce a proxy class:
class read_proxy
{
public:
read_proxy(std::istream& in) : in(in) {}
template<class T> operator T () { T x; in >> x; return x; }
private:
std::istream& in;
};
read_proxy read(std::istream& in)
{
return read_proxy(in);
}
And then use it as you originally wanted:
void foo(float) {}
int main()
{
int x = read(std::cin);
foo(read(std::cin)); // float
}
The potential problem here is if someone tries to persist the returned proxy itself, he can run into problems with lifetime (since it holds a simple reference to a stream, and the latter can potentially be destructed before the proxy is).
As the other answers indicate it is not standard compliant.
You did not show intended usage so it's a bit difficult to figure out what exactly you are after but you can implement the code yourself (see below), which can be improved more with SFINAE to avoid creating transformation templates for each specific class:
#include <iostream>
#include <sstream>
using namespace std;
struct A
{
int x;
A() : x(0) {}
};
istream& operator>>(istream& in, A& a)
{
in >> a.x;
return in;
}
ostream& operator<<(ostream& on, A& a) { return on << "A: " << a.x; }
struct B
{
int x;
B(istream& in) : x(0) { in >> x; }
};
ostream& operator<<(ostream& on, B& b) { return on << "B: " << b.x; }
struct C
{
int x;
C() : x(0) {}
static C OfStreamX(istream& in)
{
C c;
in >> c.x;
return c;
}
};
ostream& operator<<(ostream& on, C& c) { return on << "C: " << c.x; }
template <typename T> T Read(istream& in);
template <> A Read(istream& in)
{
A a;
in >> a;
return a;
}
template <> B Read(istream& in) { return B(in); }
template <> C Read(istream& in) { return C::OfStreamX(in); }
int main()
{
string data("23 45 67");
istringstream in(data);
A a = Read<A>(in);
cout << a << endl;
B b = Read<B>(in);
cout << b << endl;
C c = Read<C>(in);
cout << c << endl;
}
Output:
A: 23
B: 45
C: 67

Overloading operator<< for primitive types. Is that possible?

Hey. Is it possible to overload operator<< for primitive types? Fx lets say that I want to write a std::endl each time want to write a int. Can I overload operator<< for int, so that it automatic puts a std::endl to the output? I have tried with this,
std::ostream& operator<<(std::ostream& strm, int & i)
{
strm << i << std::endl;
return strm;
}
but it doesn't work. I cant recall the compiler error message, but I think that I'm getting operator overloading all wrong any ways.
I try to call the above overloaded operator<< in this way,
int main()
{
int i = 2;
std::out<<"Here is an int " << i;
return 0;
}
But it doesn't work at all. Maybe I can't overload POD types?
As zabzonk said, the standard library provides an (ostream&, int) overload so you can't define another.
To simulate what you were doing (though it is completely pointless in its present form :) :
class EndlinedInteger {
public:
EndlinedInteger(int i) : i(i) { }
friend ostream& operator<<(ostream&, EndlinedInteger const&);
private:
int i;
};
ostream& operator<<(ostream& out, EndlinedInteger const& ei) {
out << ei.i << endl;
return out;
}
int main()
{
EndlinedInteger i = 2;
std::cout<<"Here is an int " << i;
}
Remember that here you use << operator not only on int but also on ostream. You could derive from ostream and implement it in your own derived class, but I would suggest to make a simple macro like
#define EL(i) (i)<<std::endl
Alternatively you could make boxed int class and override the << for standard ostream and boxed int (like in answer by Iraimbilanja) class. Sounds like huge overkill but could work.
Your problem is that there is already an overload for operator << (ostream &, int), the one supplied by the C++ standard library. If you remove the overload definition and use:
#include <iostream>
int main()
{
int i = 2;
std::out<<"Here is an int " << i;
return 0;
}
things work as expected.
And BTW, compiler error messages are kind of important, so it's a good idea to remember them and quote them in posts when asking questions.
edit - std::out above should of couse be std::cout