Compiling based on container type - c++

In the code below, suppose that I decided to use deque instead of vector in the definition of mcc. How can I bypass cell.reserve(size) which is not defined for deque?
#include <vector>
#include <deque>
typedef std::vector<int> mcc;
//typedef std::deque<int> mcc;
void reserve(mcc& cell, int size)
{
cell.reserve(size);
}
int main()
{
mcc cell;
reserve(cell, 10);
return 0;
}

As the other answer and some comments have pointed out, in C++20, there are concepts, a feature which makes this task fairly trivial. However, as of now, C++20 support isn't complete in any compiler.
In the current C++ version, C++17, we don't have concepts. So, we need to use templates to emulate this concept behavior:
// The default case for can_reserve is false
template<typename T, typename = void>
struct can_reserve : std::false_type {};
// An overload of the struct allows us to verify we can call a value of type T
// If substitution doesn't fail, this overload is selected.
template<typename T>
struct can_reserve<T, std::void_t<decltype(std::declval<T>().reserve(1))>> : std::true_type {};
// With inline constexpr values, we can make this a type trait
template<typename T>
inline constexpr bool can_reserve_v = can_reserve<T>::value;
// We can then verify we can reserve with the types
static_assert(can_reserve_v<std::vector<int>>);
static_assert(!can_reserve_v<std::deque<int>>);
The function then becomes:
template<typename T>
void reserve(T& cell, int size)
{
if constexpr(can_reserve_v<T>)
cell.reserve(size);
}
Creating this kind of template is boilerplate-y and sometimes failure-prone. To solve that, we can use the detection idiom, which reduces the boilerplate and makes the code more readable:
// Using FluentCPP's is_detected implementation of the detection idiom
template<typename T>
using reserve_expression = decltype(std::declval<T&>().reserve(1));
template<typename T>
constexpr bool can_reserve_v = is_detected<reserve_expression, T>;
(The reserve function stays the same)
For completeness, the equivalent in C++20 would be:
template<typename T>
concept can_reserve = requires(T& t){
{ t.reserve(1) };
};
template<typename T>
void reserve(T& cell, int size)
{
if constexpr(can_reserve<T>)
cell.reserve(size);
}

There is a neat C++20 solution:
#include <vector>
#include <deque>
//typedef std::vector<int> mcc;
typedef std::deque<int> mcc;
mcc cell;
template<typename T>
void reserve(T& cell, int size)
{
if constexpr(requires{cell.reserve(size);}) {
cell.reserve(size);
}
}
int main()
{
reserve(cell, 10);
return 0;
}

Related

C++ wrapper around any collection type using templates

Extremely new to c++ however have a question regarding templates
Suppose I have a simple template class as defined below:
template<typename Collection>
class MySack {
private:
Collection c;
public:
typedef typename Collection::value_type value_type;
void add(const value_type& value) {
c.push_back(value);
}
};
The aim of the class being to accept any type of collection, and allow a user to insert the correct type of value for the specified typename Collection.
The obvious problem is that this is only going to work for types which have a push_back method defined, which means it would work with list however not with set.
I started reading about template specialization to see if that'd be any help, however I don't think this would provide a solution as the type contained within the set would have to be known.
How would this problem be approached in c++?
You can use std::experimental::is_detected and if constexpr to make it work:
template<class C, class V>
using has_push_back_impl = decltype(std::declval<C>().push_back(std::declval<V>()));
template<class C, class V>
constexpr bool has_push_back = std::experimental::is_detected_v<has_push_back_impl, C, V>;
template<typename Collection>
class MySack {
private:
Collection c;
public:
typedef typename Collection::value_type value_type;
void add(const value_type& value) {
if constexpr (has_push_back<Collection, value_type>) {
std::cout << "push_back.\n";
c.push_back(value);
} else {
std::cout << "insert.\n";
c.insert(value);
}
}
};
int main() {
MySack<std::set<int>> f;
f.add(23);
MySack<std::vector<int>> g;
g.add(23);
}
You can switch to insert member function, which has the same syntax for std::vector, std::set, std::list, and other containers:
void add(const value_type& value) {
c.insert(c.end(), value);
}
In C++11, you might also want to create a version for rvalue arguments:
void add(value_type&& value) {
c.insert(c.end(), std::move(value));
}
And, kind-of simulate emplace semantics (not truly in fact):
template <typename... Ts>
void emplace(Ts&&... vs) {
c.insert(c.end(), value_type(std::forward<Ts>(vs)...));
}
...
int main() {
using value_type = std::pair<int, std::string>;
MySack<std::vector<value_type>> v;
v.emplace(1, "first");
MySack<std::set<value_type>> s;
s.emplace(2, "second");
MySack<std::list<value_type>> l;
l.emplace(3, "third");
}
I started reading about template specialization to see if that'd be
any help, however I don't think this would provide a solution as the
type contained within the set would have to be known.
You can partially specialize MySack to work with std::set.
template <class T>
class MySack<std::set<T>> {
//...
};
However, this has the disadvantage that the partial specialization replaces the whole class definition, so you need to define all member variables and functions again.
A more flexible approach is to use policy-based design. Here, you add a template parameter that wraps the container-specific operations. You can provide a default for the most common cases, but users can provide their own policy for other cases.
template <class C, class V = typename C::value_type>
struct ContainerPolicy
{
static void push(C& container, const V& value) {
c.push_back(value);
}
static void pop(C& container) {
c.pop_back();
}
};
template <class C, class P = ContainerPolicy<C>>
class MySack
{
Collection c;
public:
typedef typename Collection::value_type value_type;
void add(const value_type& value) {
P::push(c, value);
}
};
In this case, it is easier to provide a partial template specialization for the default policy, because it contains only the functionality related to the specific container that is used. Other logic can still be captured in the MySack class template without the need for duplicating code.
Now, you can use MySack also with your own or third party containers that do not adhere to the STL style. You simply provide your own policy.
struct MyContainer {
void Add(int value);
//...
};
struct MyPolicy {
static void push(MyContainer& c, int value) {
c.Add(value);
}
};
MySack<MyContainer, MyPolicy> sack;
If you can use at least C++11, I suggest the creation of a template recursive struct
template <std::size_t N>
struct tag : public tag<N-1U>
{ };
template <>
struct tag<0U>
{ };
to manage precedence in case a container can support more than one adding functions.
So you can add, in the private section of your class, the following template helper functions
template <typename D, typename T>
auto addHelper (T && t, tag<2> const &)
-> decltype((void)std::declval<D>().push_back(std::forward<T>(t)))
{ c.push_back(std::forward<T>(t)); }
template <typename D, typename T>
auto addHelper (T && t, tag<1> const &)
-> decltype((void)std::declval<D>().insert(std::forward<T>(t)))
{ c.insert(std::forward<T>(t)); }
template <typename D, typename T>
auto addHelper (T && t, tag<0> const &)
-> decltype((void)std::declval<D>().push_front(std::forward<T>(t)))
{ c.push_front(std::forward<T>(t)); }
Observe that the decltype() part enable they (through SFINAE) only if the corresponding method (push_back(), insert() or push_front()) is enabled.
Now you can write add(), in the public section, as follows
template <typename T>
void add (T && t)
{ addHelper<C>(std::forward<T>(t), tag<2>{}); }
The tag<2> element make so the tag<2> addHelper() method is called, if available (if push_back() is available for type C), otherwise is called the tag<1> method (the insert() one) if available, otherwise the tag<0> method (the push_front() one) is available. Otherwise error.
Also observe the T && t and std::forward<T>(t) part. This way you should select the correct semantic: copy or move.
The following is a full working example
#include <map>
#include <set>
#include <list>
#include <deque>
#include <vector>
#include <iostream>
#include <forward_list>
#include <unordered_map>
#include <unordered_set>
template <std::size_t N>
struct tag : public tag<N-1U>
{ };
template <>
struct tag<0U>
{ };
template <typename C>
class MySack
{
private:
C c;
template <typename D, typename T>
auto addHelper (T && t, tag<2> const &)
-> decltype((void)std::declval<D>().push_back(std::forward<T>(t)))
{ c.push_back(std::forward<T>(t)); }
template <typename D, typename T>
auto addHelper (T && t, tag<1> const &)
-> decltype((void)std::declval<D>().insert(std::forward<T>(t)))
{ c.insert(std::forward<T>(t)); }
template <typename D, typename T>
auto addHelper (T && t, tag<0> const &)
-> decltype((void)std::declval<D>().push_front(std::forward<T>(t)))
{ c.push_front(std::forward<T>(t)); }
public:
template <typename T>
void add (T && t)
{ addHelper<C>(std::forward<T>(t), tag<2>{}); }
};
int main ()
{
MySack<std::vector<int>> ms0;
MySack<std::deque<int>> ms1;
MySack<std::set<int>> ms2;
MySack<std::multiset<int>> ms3;
MySack<std::unordered_set<int>> ms4;
MySack<std::unordered_multiset<int>> ms5;
MySack<std::list<int>> ms6;
MySack<std::forward_list<int>> ms7;
MySack<std::map<int, long>> ms8;
MySack<std::multimap<int, long>> ms9;
MySack<std::unordered_map<int, long>> msA;
MySack<std::unordered_multimap<int, long>> msB;
ms0.add(0);
ms1.add(0);
ms2.add(0);
ms3.add(0);
ms4.add(0);
ms5.add(0);
ms6.add(0);
ms7.add(0);
ms8.add(std::make_pair(0, 0L));
ms9.add(std::make_pair(0, 0L));
msA.add(std::make_pair(0, 0L));
msB.add(std::make_pair(0, 0L));
}

restricting the types using templates in vc++

As far my understanding goes I want to restrict only 2 types int and string for the following class, just like in java template definition with extends.
template<typename T>
typename std::enable_if<std::is_same<T,int>::value || std::is_same<T,string>::value>::type
class ExchangeSort
{
public:
void bubbleSort(T buffer[], int s);
void print(T buffer[], int s);
void bubbleSort(const vector<T>& vec);
};
But if I'm instantiating like below
ExchangeSort<int>* sortArray = new ExchangeSort<int>;
I'm getting errors for the above line ExchangeSort is undefined. What is the problem ?
SFINAE can be used to conditionally disable function overloads or template specialisations. It makes no sense to try to use it to disable a class template, since class templates cannot be overloaded. You'll be better off using a static assertion:
template<typename T>
class ExchangeSort
{
static_assert(std::is_same<T,int>::value || std::is_same<T,string>::value, "ExchangeSort requires int or string");
public:
// The rest as before
As to the errors you were getting, the code didn't make syntactic sense. enable_if can only appear where a type is expected. With functions, it's often used to wrap the return type, in which case it's syntactically similar to what you wrote. But with classes, there's no type between template and the class definition.
Here's another way which allows the possibility of adding further specialisations down the line:
#include <type_traits>
#include <vector>
#include <string>
//
// Step 1 : polyfill missing c++17 concepts
//
namespace notstd {
template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
: std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };
}
//
// Step 2 : create a test to see if a type is in a list
//
namespace detail {
template<class T, class...Us>
struct is_one_of : notstd::disjunction< std::is_same<T, Us>... > {};
}
template<class T, class...Us>
static constexpr auto IsOneOf = detail::is_one_of<T, Us...>::value;
//
// Step 3 : declare the default specialisation, but don't define it
//
template<class T, typename Enable = void>
struct ExchangeSort;
//
// Step 4 : define the specialisations we want
//
template<typename T>
class ExchangeSort<T, std::enable_if_t<IsOneOf<T, int, std::string>>>
{
public:
void bubbleSort(T buffer[], int s);
void print(T buffer[], int s);
void bubbleSort(const std::vector<T>& vec);
};
//
// Test
//
int main()
{
auto esi = ExchangeSort<int>();
auto ess = ExchangeSort<std::string>();
// won't compile
// auto esd = ExchangeSort<double>();
}

Use boost::hash_value to define std::hash in C++11

Is there an easy way to do the following with C++11 & Boost:
use the standard definitions of std::hash whenever available from <functional>
use boost::hash_value to define std::hash in those cases where std::hash is missing but boost::hash_value is available in <boost/functional/hash.hpp>.
For example:
std::hash<std::vector<bool>> should come from the standard library,
std::hash<std::vector<unsigned>> should be implemented with boost::hash_value.
The first idea that comes to mind is to use SFINAE and try std::hash<> if possible and otherwise use boost::hash_value(), like this:
#include <string>
#include <functional>
#include <type_traits>
#include <boost/functional/hash.hpp>
struct my_struct_0 {
std::string s;
};
template <typename T>
struct has_std_hash_subst { typedef void type; };
template <typename T, typename C = void>
struct has_std_hash : std::false_type {};
template <typename T>
struct has_std_hash<
T,
typename has_std_hash_subst<decltype( std::hash<T>()(T()) ) >::type
> : std::true_type {};
template <typename T>
static typename std::enable_if<has_std_hash<T>::value, size_t>::type
make_hash(const T &v)
{
return std::hash<T>()(v);
}
template <typename T>
static typename std::enable_if<(!has_std_hash<T>::value), size_t>::type
make_hash(const T &v)
{
return boost::hash_value(v);
}
int main()
{
make_hash(std::string("Hello, World!"));
make_hash(my_struct_0({ "Hello, World!" }));
}
Unfortunately, there is always a default specialization of std::hash that triggers static_assert failure. This may not be the case with other libraries but it is the case with GCC 4.7.2 (see bits/functional_hash.h:60):
/// Primary class template hash.
template<typename _Tp>
struct hash : public __hash_base<size_t, _Tp>
{
static_assert(sizeof(_Tp) < 0,
"std::hash is not specialized for this type");
size_t operator()(const _Tp&) const noexcept;
};
So the above SFINAE approach doesn't work — static_assert in there is a show-stopper. Therefore, you cannot really determine when std::hash is available.
Now, this does not really answer your question but might come handy — it is possible to do this trick the other way around — check for Boost implementation first and only then fall back to std::hash<>. Consider the below example that uses boost::hash_value() if it is available (i.e. for std::string and my_struct_0) and otherwise uses std::hash<> (i.e. for my_struct_1):
#include <string>
#include <functional>
#include <type_traits>
#include <boost/functional/hash.hpp>
struct my_struct_0 {
std::string s;
};
struct my_struct_1 {
std::string s;
};
namespace boost {
size_t hash_value(const my_struct_0 &v) {
return boost::hash_value(v.s);
}
}
namespace std {
template <>
struct hash<my_struct_1> {
size_t operator()(const my_struct_1 &v) const {
return std::hash<std::string>()(v.s);
}
};
}
template <typename T>
struct has_boost_hash_subst { typedef void type; };
template <typename T, typename C = void>
struct has_boost_hash : std::false_type {};
template <typename T>
struct has_boost_hash<
T,
typename has_boost_hash_subst<decltype(boost::hash_value(T()))>::type
> : std::true_type {};
template <typename T>
static typename std::enable_if<has_boost_hash<T>::value, size_t>::type
make_hash(const T &v)
{
size_t ret = boost::hash_value(v);
std::cout << "boost::hash_value(" << typeid(T).name()
<< ") = " << ret << '\n';
return ret;
}
template <typename T>
static typename std::enable_if<(!has_boost_hash<T>::value), size_t>::type
make_hash(const T &v)
{
size_t ret = std::hash<T>()(v);
std::cout << "std::hash(" << typeid(T).name()
<< ") = " << ret << '\n';
return ret;
}
int main()
{
make_hash(std::string("Hello, World!"));
make_hash(my_struct_0({ "Hello, World!" }));
make_hash(my_struct_1({ "Hello, World!" }));
}
Hope it helps.
UPDATE: Perhaps you could use the hack described here as pointed out by #ChristianRau and make the first SFINAE approach work! Though it is very dirty :)
My answer might not be correct, but I will try to explain why I think that the answer is no.
I don't think that std::hash<T> and boost:hash<T> can be used interchangeably, so I've tried hiding object creation (even if this is not perfect solution), and return their result, which is size_t. Method should be of course chosen at compile time, so function dispatch is what comes to my mind, sample code:
template <typename T>
size_t createHash(const T& t, false_type)
{
return boost::hash<T>()(t);
}
template <typename T>
size_t createHash(const T& t, true_type)
{
return std::hash<T>()(t);
}
template<typename T>
size_t createHash(const T& t)
{
return createHash<T>(t, std::is_XXX<T>::type());
}
int main()
{
vector<unsigned> v; v.push_back(1);
auto h1 = createHash(v);
cout << " hash: " << h1;
//hash<vector<unsigned> > h2;
}
The idea of this code is simple: if you can construct type of type std::hash<T>, choose second implementation, if not - choose first one.
If the first implementation is chosen, code compiles without a problem, you can check it by using fe. std::is_array<T>::type() in a wrapper function, which is of course not true, so boost::hash implementation will be choosed. However, if you use a trait which will return true_t for a vector<unsigned>, like fe. std::is_class<T>::type() then the compiler will report "C++ Standard doesn't provide...", which is a result of a static_assert.
For this to work, we would need to force compiler to return true_t if a type is really constructible (it doesn't fail static_assert) and false_t if it doesn't. However, I don't think there is a possibility to do that.

ADL does not work in the specific situation

I've made is_iterable template as below - which checks that free functions begin/end are available (in the context of ADL) and return proper iterator object. (Which is the requirement for iterable object in ranged-for loop)
#include <utility>
#include <iterator>
#include <type_traits>
#include <vector>
template <typename T>
typename std::add_rvalue_reference<T>::type declval(); // vs2010 does not support std::declval - workaround
template <bool b>
struct error_if_false;
template <>
struct error_if_false<true>
{
};
template<typename U>
struct is_input_iterator
{
enum {
value = std::is_base_of<
std::input_iterator_tag,
typename std::iterator_traits<U>::iterator_category
>::value
};
};
template<typename T>
struct is_iterable
{
typedef char yes;
typedef char (&no)[2];
template<typename U>
static auto check(U*) -> decltype(
error_if_false<
is_input_iterator<decltype(begin(declval<U>()))>::value
>(),
error_if_false<
is_input_iterator<decltype(end(declval<U>()))>::value
>(),
error_if_false<
std::is_same<
decltype(begin(declval<U>())),
decltype(end(declval<U>()))
>::value
>(),
yes()
);
template<typename>
static no check(...);
public:
static const bool value = (sizeof(check<typename std::decay<T>::type>(nullptr)) == sizeof(yes));
};
#include <cstdio>
void write(int a)
{
printf("%d\n", a);
}
template<typename T>
typename std::enable_if<is_iterable<T>::value>::type write(const T& a)
{
for (auto i = begin(a), e = end(a); i != e; ++i) {
write(*i);
}
}
int main()
{
write(10);
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
write(a);
}
Above code exactly works as intended in vs2010, but not in gcc. Moreover, when I put the some random free function named 'begin', as below, it becomes broken even in vs2010.
int begin(int)
{
}
How can I make the code works? Also, any suggestion that improves the "is_iterable" concept checker would be appreciated.
added: "write" function is just a concept demonstration example - please don't invest your precious time to it. (I know it's not the best code :( ) The part needs some attention is ADL behaviour and "is_iterable" template :)
After adding std:: to begin/end - your code compiles and runs under gcc-4.6
Improvement suggestion: replace error_if_false with of enable_if
write(a); should be defined through the operator as Jerry said. Maybe make it more consise so that your code is cleaner.

specific syntax question

Is it possible to create template to the initialization like:
template <typename C> typename C::value_type fooFunction(C& c) {...};
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));
In general i'm interested is it possible to specify template using integer (ie. 0) instead of true type name.
And how to achieve above?
I'm not completely clear on what you're asking, but the following snippet works for me:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename C>
typename C::value_type fooFunction(const C & c) { return 0; };
/* note that fooFunction takes a ref-to-const, not a reference */
template<int N>
struct cont
{
public:
typedef int value_type;
cont(vector<string> vec) {};
};
int main()
{
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));
}
Two changes worth noting:
An integer is not a type, so if cont is declared template <typename T>, what you have written will not work. template <int N> is the proper way to parameterize over an integral value, as templatetypedef mentioned.
I'm not sure how cont<> is defined, but from your usage it must be an object you are constructing as a temporary. You will have trouble passing this temporary as a reference into fooFunction. Note that my example above passes C as reference-to-const instead.
Yes, you can parameterize templates over non-type arguments like integers, pointers, and other templates. For example:
template <typename T, int N> struct Array {
T data[N];
/* ... other functions ... */
};
These templates work just like all the other templates you've seen, except that they're parameterized over integral values rather than types.
This link has some more info on the subject. "Modern C++ Design" and "C++ Templates: The Complete Guide" also have lots of info on how to do this.
Is this what you are after? Non-type template parameters:
template<int n> class Cont
{
public:
typedef int value_type;
};
template<>
class Cont<0>
{
public:
typedef double value_type;
value_type convert(const std::string& s) const
{
return atof(s.c_str());
}
};
template<>
class Cont<1>
{
public:
typedef long value_type;
value_type convert(const std::string& s) const
{
return atoi(s.c_str());
}
};
template <int n> typename Cont<n>::value_type fooFunction(const Cont<n>& cont, const std::string& s)
{
return cont.convert(s);
}
void test()
{
Cont<0> c0;
Cont<1> c1;
double d = fooFunction(c0,"1.0");
int i = fooFunction(c1, "-17");
}