How to initialize a set from a vector and provide a compare function? - stl

I need to get the unique elements of a vector, sorted by a criteria implemented in a function. As you can see the vector, and the resulting set, "only" contain references to the objects to be sorted.
The following minimal example works, as long a I do not use the compare function ˋref_wrp_ltˋ.
#include <functional>
#include <set>
#include <vector>
template <class T> constexpr bool ref_wrp_lt(const std::reference_wrapper<T>&lhs, const std::reference_wrapper<T>&rhs)
{
return lhs.get() < rhs.get();
}
class A
{
};
int main()
{
std::vector<std::reference_wrapper<A>> my_vec = std::vector<std::reference_wrapper<A>>();
std::set<std::reference_wrapper<A>, bool(*)(const std::reference_wrapper<A>&, const std::reference_wrapper<A>&)> my_set(my_vec.begin(), my_vec.end(), &ref_wrp_lt);
return 0;
}
However, when I provide it, it seems I have to provide an allocator. Is this really the case and if yes, how can I always use the default allocator?
P.S.: I am new to STL and object oriented programming in C++.

The missing part in the example code is an operator< for class A. Adding it ie. as follows makes the code compilable:
class A
{
public:
bool operator<(const A &other) {
// TODO: add logic for comparison
return false;
}
};

Related

How to provide cpp class destructor member information in cython [duplicate]

I'm using the pimpl-idiom with std::unique_ptr:
class window {
window(const rectangle& rect);
private:
class window_impl; // defined elsewhere
std::unique_ptr<window_impl> impl_; // won't compile
};
However, I get a compile error regarding the use of an incomplete type, on line 304 in <memory>:
Invalid application of 'sizeof' to an incomplete type 'uixx::window::window_impl'
For as far as I know, std::unique_ptr should be able to be used with an incomplete type. Is this a bug in libc++ or am I doing something wrong here?
Here are some examples of std::unique_ptr with incomplete types. The problem lies in destruction.
If you use pimpl with unique_ptr, you need to declare a destructor:
class foo
{
class impl;
std::unique_ptr<impl> impl_;
public:
foo(); // You may need a def. constructor to be defined elsewhere
~foo(); // Implement (with {}, or with = default;) where impl is complete
};
because otherwise the compiler generates a default one, and it needs a complete declaration of foo::impl for this.
If you have template constructors, then you're screwed, even if you don't construct the impl_ member:
template <typename T>
foo::foo(T bar)
{
// Here the compiler needs to know how to
// destroy impl_ in case an exception is
// thrown !
}
At namespace scope, using unique_ptr will not work either:
class impl;
std::unique_ptr<impl> impl_;
since the compiler must know here how to destroy this static duration object. A workaround is:
class impl;
struct ptr_impl : std::unique_ptr<impl>
{
~ptr_impl(); // Implement (empty body) elsewhere
} impl_;
As Alexandre C. mentioned, the problem comes down to window's destructor being implicitly defined in places where the type of window_impl is still incomplete. In addition to his solutions, another workaround that I've used is to declare a Deleter functor in the header:
// Foo.h
class FooImpl;
struct FooImplDeleter
{
void operator()(FooImpl *p);
};
class Foo
{
...
private:
std::unique_ptr<FooImpl, FooImplDeleter> impl_;
};
// Foo.cpp
...
void FooImplDeleter::operator()(FooImpl *p)
{
delete p;
}
Note that using a custom Deleter function precludes the use of std::make_unique (available from C++14), as already discussed here.
use a custom deleter
The problem is that unique_ptr<T> must call the destructor T::~T() in its own destructor, its move assignment operator, and unique_ptr::reset() member function (only). However, these must be called (implicitly or explicitly) in several PIMPL situations (already in the outer class's destructor and move assignment operator).
As already pointed out in another answer, one way to avoid that is to move all operations that require unique_ptr::~unique_ptr(), unique_ptr::operator=(unique_ptr&&), and unique_ptr::reset() into the source file where the pimpl helper class is actually defined.
However, this is rather inconvenient and defies the very point of the pimpl idoim to some degree. A much cleaner solution that avoids all that is to use a custom deleter and only move its definition into the source file where the pimple helper class lives. Here is a simple example:
// file.h
class foo
{
struct pimpl;
struct pimpl_deleter { void operator()(pimpl*) const; };
std::unique_ptr<pimpl,pimpl_deleter> m_pimpl;
public:
foo(some data);
foo(foo&&) = default; // no need to define this in file.cc
foo&operator=(foo&&) = default; // no need to define this in file.cc
//foo::~foo() auto-generated: no need to define this in file.cc
};
// file.cc
struct foo::pimpl
{
// lots of complicated code
};
void foo::pimpl_deleter::operator()(foo::pimpl*ptr) const { delete ptr; }
Instead of a separate deleter class, you can also use a free function or static member of foo:
class foo {
struct pimpl;
static void delete_pimpl(pimpl*);
using deleter = void(&)(pimpl*);
std::unique_ptr<pimpl,deleter> m_pimpl;
public:
foo(some data);
};
Probably you have some function bodies within .h file within class that uses incomplete type.
Make sure that within your .h for class window you have only function declaration. All function bodies for window must be in .cpp file. And for window_impl as well...
Btw, you have to explicitly add destructor declaration for windows class in your .h file.
But you CANNOT put empty dtor body in you header file:
class window {
virtual ~window() {};
}
Must be just a declaration:
class window {
virtual ~window();
}
To add to the other's replies about the custom deleter, in our internal "utilities library" I added a helper header to implement this common pattern (std::unique_ptr of an incomplete type, known only to some of the TU to e.g. avoid long compile times or to provide just an opaque handle to clients).
It provides the common scaffolding for this pattern: a custom deleter class that invokes an externally-defined deleter function, a type alias for a unique_ptr with this deleter class, and a macro to declare the deleter function in a TU that has a complete definition of the type. I think that this has some general usefulness, so here it is:
#ifndef CZU_UNIQUE_OPAQUE_HPP
#define CZU_UNIQUE_OPAQUE_HPP
#include <memory>
/**
Helper to define a `std::unique_ptr` that works just with a forward
declaration
The "regular" `std::unique_ptr<T>` requires the full definition of `T` to be
available, as it has to emit calls to `delete` in every TU that may use it.
A workaround to this problem is to have a `std::unique_ptr` with a custom
deleter, which is defined in a TU that knows the full definition of `T`.
This header standardizes and generalizes this trick. The usage is quite
simple:
- everywhere you would have used `std::unique_ptr<T>`, use
`czu::unique_opaque<T>`; it will work just fine with `T` being a forward
declaration;
- in a TU that knows the full definition of `T`, at top level invoke the
macro `CZU_DEFINE_OPAQUE_DELETER`; it will define the custom deleter used
by `czu::unique_opaque<T>`
*/
namespace czu {
template<typename T>
struct opaque_deleter {
void operator()(T *it) {
void opaque_deleter_hook(T *);
opaque_deleter_hook(it);
}
};
template<typename T>
using unique_opaque = std::unique_ptr<T, opaque_deleter<T>>;
}
/// Call at top level in a C++ file to enable type %T to be used in an %unique_opaque<T>
#define CZU_DEFINE_OPAQUE_DELETER(T) namespace czu { void opaque_deleter_hook(T *it) { delete it; } }
#endif
May be not a best solution, but sometimes you may use shared_ptr instead.
If course it's a bit an overkill, but... as for unique_ptr, I'll perhaps wait 10 years more until C++ standard makers will decide to use lambda as a deleter.
Another side.
Per your code it may happen, that on destruction stage window_impl will be incomplete. This could be a reason of undefined behaviour.
See this:
Why, really, deleting an incomplete type is undefined behaviour?
So, if possible I would define a very base object to all your objects, with virtual destructor. And you're almost good. You just should keep in mind that system will call virtual destructor for your pointer, so you should define it for every ancestor. You should also define base class in inheritance section as a virtual (see this for details).
Using extern template
The issue with using std::unique_ptr<T> where T is an incomplete type is that unique_ptr needs to be able to delete an instance of T for various operations. The class unique_ptr uses std::default_delete<T> to delete the instance. Hence, in an ideal world, we would just write
extern template class std::default_delete<T>;
to prevent std::default_delete<T> from being instantiated. Then, declaring
template class std::default_delete<T>;
at a place where T is complete, would instantiate the template.
The issue here is that default_delete actually defines inline methods that will not be instantiated. So, this idea does not work. We can, however, work around this problem.
First, let us define a deleter that does not inline the call operator.
/* --- opaque_ptr.hpp ------------------------------------------------------- */
#ifndef OPAQUE_PTR_HPP_
#define OPAQUE_PTR_HPP_
#include <memory>
template <typename T>
class opaque_delete {
public:
void operator() (T* ptr);
};
// Do not move this method into opaque_delete, or it will be inlined!
template <typename T>
void opaque_delete<T>::operator() (T* ptr) {
std::default_delete<T>()(ptr);
}
Furthermore, for ease of use, define a type opaque_ptr which combines unique_ptr with opaque_delete, and analogously to std::make_unique, we define make_opaque.
/* --- opaque_ptr.hpp cont. ------------------------------------------------- */
template <typename T>
using opaque_ptr = std::unique_ptr<T, opaque_delete<T>>;
template<typename T, typename... Args>
inline opaque_ptr<T> make_opaque(Args&&... args)
{
return opaque_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif
The type opaque_delete can now be used with the extern template construction. Here is an example.
/* --- foo.hpp -------------------------------------------------------------- */
#ifndef FOO_HPP_
#define FOO_HPP_
#include "opaque_ptr.hpp"
class Foo {
public:
Foo(int n);
void print();
private:
struct Impl;
opaque_ptr<Impl> m_ptr;
};
// Do not instantiate opaque_delete.
extern template class opaque_delete<Foo::Impl>;
#endif
Since we prevent opaque_delete from being instantiated this code compiles without errors. To make the linker happy, we instantiate opaque_delete in our foo.cpp.
/* --- foo.cpp -------------------------------------------------------------- */
#include "foo.hpp"
#include <iostream>
struct Foo::Impl {
int n;
};
// Force instantiation of opaque_delete.
template class opaque_delete<Foo::Impl>;
The remaining methods could be implemented as follows.
/* --- foo.cpp cont. -------------------------------------------------------- */
Foo::Foo(int n)
: m_ptr(new Impl)
{
m_ptr->n = n;
}
void Foo::print() {
std::cout << "n = " << m_ptr->n << std::endl;
}
The advantage of this solution is that, once opaque_delete is defined, the required boilerplate code is rather small.

SWIG parser error

I have following header file.
#include <string>
namespace A {
namespace B {
struct Msg {
std::string id;
std::string msg;
Msg(std::string new_id, std::string new_msg)
: id(new_id), msg(new_msg)
{
}
};
template<bool HAS_ID>
class ID {
public:
template<typename TOBJ>
auto get(TOBJ parent) -> decltype(parent.id()) {
return parent.id();
}
};
} // namespace B
} // namespace A
When i swig it, it gives me an error
Error: Syntax error in input(3). at line 20 pointing to line
auto get(TOBJ parent) -> decltype(parent.id())
Target language is Java
How can i fix this problem? I only want to create wrapper for Msg struct and for nothing else in the header. As this looks like a Swig parser error, using %ignore directive does not seem to work.
Thank you
Although SWIG 3.x added limited decltype support it looks like the case you have is unsupported currently. (See decltype limitations)
I think the best you'll get for now is to surround the offending code in preprocessor macros to hide it, e.g.:
#include <string>
namespace A {
namespace B {
struct Msg {
std::string id;
std::string msg;
Msg(std::string new_id, std::string new_msg)
: id(new_id), msg(new_msg)
{
}
};
template<bool HAS_ID>
class ID {
public:
#ifndef SWIG
template<typename TOBJ>
auto get(TOBJ parent) -> decltype(parent.id()) {
return parent.id();
}
#endif
};
} // namespace B
} // namespace A
If you can't edit the file like that for whatever reason there are two options:
Don't use %include with the header file that doesn't parse. Instead write something like:
%{
#include "header.h" // Not parsed by SWIG here though
%}
namespace A {
namespace B {
struct Msg {
std::string id;
std::string msg;
Msg(std::string new_id, std::string new_msg)
: id(new_id), msg(new_msg)
{
}
};
} // namespace B
} // namespace A
in your .i file, which simply tells SWIG about the type you want to wrap and glosses over the one that doesn't work.
Alternatively get creative with the pre-processor and find a way to hide it using a bodge, inside your .i file you could write something like:
#define auto // \
void ignore_me();
%ignore ignore_me;
Another similar bodge would be to hide the contents of decltype with:
#define decltype(x) void*
Which just tells SWIG to assume all decltype usage is a void pointer. (Needs SWIG 3.x and could be combined with %ignore which ought to do the ignore, or a typemap to really fix it)

What's the correct syntax for a template class member fucntion to return a struct type?

In Storing C++ template function definitions in a .CPP file one can learn how to store a template implementation in .cpp. However I failed to do it if the return type is a struct which is defined inside the class. See,
template<typename T>
class C1
{
public:
struct s {
int x;
};
s GetS();
private:
s m_sInt;
};
in its .cpp, the below code will generate syntax errors.
template<typename T>
C1<T>::s C1<T>::GetS()
{
return m_sInt;
}
Wonder what the right syntax should be in this case.
template<typename T>
typename C1<T>::s C1<T>::GetS()
{
return m_sInt;
}
The behaviour of compiler is explained in other questions about nested templates with dependent scope, e.g. Nested templates with dependent scope or Dependent scope and nested templates

How do I write variadic templates, that can't accept zero arguments?

Here is a variadic template that prints parameters.
#include <string>
#include <iostream>
void Output() {
std::cout<<std::endl;
}
template<typename First, typename ... Strings>
void Output(First arg, const Strings&... rest) {
std::cout<<arg<<" ";
Output(rest...);
}
int main() {
Output("I","am","a","sentence");
Output("Let's","try",1,"or",2,"digits");
Output(); //<- I do not want this to compile, but it does.
return 0;
}
Is there a way to get this functionality without having the "no parameter" call work, and without having to write two functions every time?
You might want to keep the separation of the first and the rest of the parameters, you can use:
template<typename First, typename ... Rest>
void Output(First&& first, Rest&&... rest) {
std::cout << std::forward<First>(first);
int sink[]{(std::cout<<" "<<std::forward<Rest>(rest),0)... };
(void)sink; // silence "unused variable" warning
std::cout << std::endl;
}
Note that I used perfect forwarding to avoid copying any parameters. The above has the additional benefit to avoid recursion and therefore is likely to produce better (faster) code.
The way I wrote sink also guarantees that the expressions expanded from rest are evaluated left-to-right - which is important when compared to the naïve approach of just writing a helper function template<typename...Args>void sink(Args&&...){}.
Live example
Call the function from a forwarding type function and have a static_assert like this:
template <typename ... Args>
void forwarder(Args ... args) {
static_assert(sizeof...(args),"too small");
Output(args...);
}
As far as I see there are two questsions:
How to avoid Output() calls with no parameters.
Is there a simpler way to end the compile time recursion?
My solution to item 1 is as follows:
template<typename T>
void Output(const T & string) {
std::cout<<string<<std::endl;
}
template<typename First, typename ... Strings>
void Output(const First & arg, const Strings & ... rest) {
std::cout<<arg<<" ";
Output(rest...);
}
Basically, instead of ending the recursion when the template list is empty, I end it when it only contains one type. There is one difference between the above and the code from the question: if does not output any space after the last item. Instead it just outputs the newline.
For question number two see the answer by Daniel Frey above. I really liked this solution, although it took some time to grasp it (and I upvoted the answer). At the same time I find that it makes the code harder to read/understand and therefore harder to maintain. Currently I would not not use that solution in anything but small personal code snippets.

What are some other languages that support "partial specialization"?

Partial template specialization is one of the most important concepts for generic programming in C++. For example: to implement a generic swap function:
template <typename T>
void swap(T &x, T &y) {
const T tmp = x;
y = x;
x = tmp;
}
To specialize it for a vector to support O(1) swap:
template <typename T, class Alloc>
void swap(vector<T, Alloc> &x, vector<T, Alloc> &y) { x.swap(y); }
So you can always get optimal performance when you call swap(x, y) in a generic function;
Much appreciated, if you can post the equivalent (or the canonical example of partial specialization of the language if the language doesn't support the swap concept) in alternative languages.
EDIT: so it looks like many people who answered/commented really don't known what partial specialization is, and that the generic swap example seems to get in the way of understanding by some people. A more general example would be:
template <typename T>
void foo(T x) { generic_foo(x); }
A partial specialization would be:
template <typename T>
void foo(vector<T> x) { partially_specialized_algo_for_vector(x); }
A complete specialization would be:
void foo(vector<bool> bitmap) { special_algo_for_bitmap(bitmap); }
Why this is important? because you can call foo(anything) in a generic function:
template <typename T>
void bar(T x) {
// stuff...
foo(x);
// more stuff...
}
and get the most appropriate implementation at compile time. This is one way for C++ to achieve abstraction w/ minimal performance penalty.
Hope it helps clearing up the concept of "partial specialization". In a way, this is how C++ do type pattern matching without needing the explicit pattern matching syntax (say the match keyword in Ocaml/F#), which sometimes gets in the way for generic programming.
D supports partial specialization:
Language overview
Template feature comparison (with C++ 98 and 0x).
(scan for "partial" in the above links).
The second link in particular will give you a very detailed breakdown of what you can do with template specialization, not only in D but in C++ as well.
Here's a D specific example of swap. It should print out the message for the swap specialized for the Thing class.
import std.stdio; // for writefln
// Class with swap method
class Thing(T)
{
public:
this(T thing)
{
this.thing = thing;
}
// Implementation is the same as generic swap, but it will be called instead.
void swap(Thing that)
{
const T tmp = this.thing;
this.thing = that.thing;
that.thing = tmp;
}
public:
T thing;
}
// Swap generic function
void swap(T)(ref T lhs, ref T rhs)
{
writefln("Generic swap.");
const T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void swap(T : Thing!(U))(ref T lhs, ref T rhs)
{
writefln("Specialized swap method for Things.");
lhs.swap(rhs);
}
// Test case
int main()
{
auto v1 = new Thing!(int)(10);
auto v2 = new Thing!(int)(20);
assert (v1.thing == 10);
assert (v2.thing == 20);
swap(v1, v2);
assert (v1.thing == 20);
assert (v2.thing == 10);
return 0;
}
I am afraid that C# does not support partial template specialization.
Partial template specialization means:
You have a base class with two or more templates (generics / type parameters).
The type parameters would be <T, S>
In a derived (specialized) class you indicate the type of one of the type parameters.
The type parameters could look like this <T, int>.
So when someone uses (instantiates an object of) the class where the last type parameter is an int, the derived class is used.
Haskell has overlapping instances as an extension:
class Sizable a where
size :: a -> Int
instance Collection c => Sizable c where
size = length . toList
is a function to find size of any collection, which can have more specific instances:
instance Sizable (Seq a) where
size = Seq.length
See also Advanced Overlap on HaskellWiki.
Actually, you can (not quite; see below) do it in C# with extension methods:
public Count (this IEnumerable<T> seq) {
int n = 0;
foreach (T t in seq)
n++;
return n;
}
public Count (this T[] arr) {
return arr.Length;
}
Then calling array.Count() will use the specialised version. "Not quite" is because the resolution depends on the static type of array, not on the run-time type. I.e. this will use the more general version:
IEnumerable<int> array = SomethingThatReturnsAnArray();
return array.Count();
C#:
void Swap<T>(ref T a, ref T b) {
var c = a;
a = b;
b = c;
}
I guess the (pure) Haskell-version would be:
swap :: a -> b -> (b,a)
swap a b = (b, a)
Java has generics, which allow you to do similar sorts of things.