Google mock does not compile with boost::variant of std::vector - boost

I am trying to create Google Mock object for some interface class which uses boost::variant
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <boost/variant.hpp>
#include <vector>
typedef std::vector<int> VectorOfInt;
typedef boost::variant<VectorOfInt> VariantOfVector;
class InterfaceClass
{
public:
virtual ~InterfaceClass() {}
virtual void SetSome( const VariantOfVector& ) = 0;
virtual const VariantOfVector& GetSome() const = 0;
};
class MockInterfaceClass
{
public:
MOCK_METHOD1( SetSome, void( const VariantOfVector& ) );
MOCK_CONST_METHOD0( GetSome, const VariantOfVector&() );
};
When I compile it with
g++ mytest.cpp -o mytest
i get
/usr/include/boost/variant/detail/variant_io.hpp:64: error: no match for ‘operator<<’ in ‘((const boost::detail::variant::printer > >*)this)->boost::detail::variant::printer > >::out_ << operand’
Does boost::variant work with std::vector? It seems boost::variant works with any type I define but std:vector. Why?
Boost version - 1.45
g++ version - 4.4.5

It seems that the mock attempts to apply operator << to your variant. You have to define operator << for its contents, i.e. for std::vector template.

As Igor R. answered, you need to add operator << (without namespace) like this:
std::ostream& operator <<(std::ostream& out, VariantOfVector const& rhs)
{
//Print or apply your visitor to **rhs**
return out;
}

Related

How to derive abstract template classes, with template-types as function parameters (C++11)

I've been assigned to write a class "binaryExpressionTree" which is derived from the abstract template class "binaryTreeType." binaryExpressionTree is of type String. As part of the assignment, I have to override these 3 virtual functions from binaryTreeType:
//Header File Binary Search Tree
#ifndef H_binaryTree
#define H_binaryTree
#include <iostream>
using namespace std;
//Definition of the Node
template <class elemType>
struct nodeType
{
elemType info;
nodeType<elemType> *lLink;
nodeType<elemType> *rLink;
};
//Definition of the class
template <class elemType>
class binaryTreeType
{
public:
virtual bool search(const elemType& searchItem) const = 0;
virtual void insert(const elemType& insertItem) = 0;
virtual void deleteNode(const elemType& deleteItem) = 0;
binaryTreeType();
//Default constructor
};
binaryTreeType<elemType>::binaryTreeType()
{
}
#endif
Here is what I have so far for binaryExpressionTree:
#define EXPRESSIONTREE_H
#include "binaryTree.h"
#include <iostream>
#include <string>
class binaryExpressionTree : public binaryTreeType<string> {
public:
void buildExpressionTree(string buildExpression);
double evaluateExpressionTree();
bool search(const string& searchItem) const = 0;
void insert(const string& insertItem) = 0;
void deleteNode(const string& deleteItem) = 0;
};
And here's binaryExpressionTree.cpp:
#include <string>
#include <cstring>
#include <stack>
#include <cstdlib>
#include <cctype>
#include "binaryExpressionTree.h"
#include "binaryTree.h"
using namespace std;
bool binaryExpressionTree::search(const string& searchItem) const {
return false;
}
void binaryExpressionTree::insert(const string& insertItem) {
cout << "this";
}
void binaryExpressionTree::deleteNode(const string& deleteItem) {
cout << "this";
}
Here's main.cpp:
#include <iostream>
#include <iomanip>
#include <fstream>
#include "binaryExpressionTree.h"
int main()
{
binaryExpressionTree mainTree = binaryExpressionTree(); //Error:[cquery] allocating an object of abstract class type 'binaryExpressionTree'
return 0;
}
The problem is, since binaryExpressionTree is a derived class of type String, it doesn't know what "elemType" means and I would need to change searchItem, insertItem and deleteItem
to string& objects. But once I do, the compiler no longer recognizes that I am overriding virtual functions (as I've changed their parameters), and declares binaryExpressionTree to be an abstract class. How do I work around this, so that I can override the functions and make binaryExpressionTree non-abstract?
Assuming the abstract class is defined like this:
template <typename elemType>
class binaryTreeType { ... }
You should define your class as follows:
class binaryExpressionTree : public binaryTreeType<String> { ... }
EDIT: original question was edited.
You are incorrectly declaring the overriding functions (inside binaryExpressionTree).
Your declaration is like this:
bool search(const string& searchItem) const = 0;
Such declaration creates a pure virtual method (because of = 0 at the end of the declaration. A pure virtual method (aka an abstract method) is a method which must be overridden by a deriving class. Thus, binaryTreeType declared its methods pure virtual, in order for you to implement, in binaryExpressionTree.
Classes which have abstract methods which are not implemented yet, cannot be instantiated - that is the error your compiler is generating.
Instead, you should declare your methods like this:
virtual bool search(const elemType& searchItem) const;
Such declaration creates regular virtual function, which would override the parent implementation (which is non-existent, at this case).
TL;DR - remove = 0.

boost fusion why there is different result in c++11 and c++03?

Why the following type as_vet_type is boost::fusion::vector2<const int, const int> when compiling with C++03 and boost::fusion::vector<int, int> when compiling with c++11 ? const is missing with c++11. Is this a bug or feature ?
I tested this with boost 1.60.
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/container/vector/vector_fwd.hpp>
#include <boost/fusion/include/vector_fwd.hpp>
#include <boost/fusion/algorithm/transformation/transform.hpp>
#include <boost/fusion/include/transform.hpp>
#include <boost/fusion/container/vector/convert.hpp>
#include <boost/fusion/include/as_vector.hpp>
struct functor
{
template<class> struct result;
template<class F, class T>
struct result<F(T)> {
typedef const int type;
};
template<class T>
typename result<functor(T) >::type
operator()(T x) const;
};
int main()
{
typedef boost::fusion::vector<const int & ,char &> cont_type;
typedef typename boost::fusion::result_of::transform<cont_type ,functor >::type view_type;
typedef typename boost::fusion::result_of::as_vector<view_type>::type as_vec_type;
as_vec_type asd;
asd.x;
return 0;
}
I got a comment from someone but unfortunetly it is no longer visible :(
Anyway thanks to that comment i figured out what is happenning.
It turns out that this issue is related boost::result_of and not to boost::fusion.
boost::result_of can behave diffrently in c++11 when decltype is used and in c++03.
boost::result_of documentation describes this diffrence in part "Non-class prvalues and cv-qualification".
I can provide this simplified explanation.
In C++11 , in this function declaration: const int f(); const is simply ignored by compiler and f signature becomes int f(); and thats why decltype(const int f()); is int.
GCC 5.3.2 will even produce the following warning if you declare const int f();
prog.cc:5:13: warning: type qualifiers ignored on function return type
[-Wignored-qualifiers] const int f()

protected members in a template deduction context: compilation error, substitution fails, or succeeds?

g++ 5.2.1 fails to compile when it encounters a private method's address in a template deduction context whereas clang 3.5 only discards the specialization.
g++ 5.2.1 can access protected members of parents/friends in a class template parameter list when clang 3.5 sometimes fail to do so.
Which are wrong in which cases?
More precisely:
Should the compiler cause a hard error when trying to access a non accessible protected/private member in a template deduction context? Am I doing something wrong in my first example?
If not, should the compiler discard a specialization when trying to access (in a template deduction context) a protected member owned by:
a base class of this specific specialization
a class which declared this specific instantiation as a friend
a friend class which declared any instantiation of this template as a friend
The first question seems to have already been answered here (and the answer seems to be "no, the code isn't ill-formed and the compiler should simply discard this specialization"). However, since it's a prerequisite to the second question (and g++ 5.2.1 doesn't seem to agree), I want to be absolutely sure that it's g++ 5.2.1 which is wrong, not me.
Longer version with examples
I would like to make traits able to detect whether some functions/methods are implemented, even if they are protected members of some class (if you find this odd, I'll explain why I want to do this at the end of this question so that you can tell me I'm completely wrong, should learn how to design my classes, and maybe suggest me a cleaner way to do so).
My problem is that each of my attempts fail on either clang or g++ (oddly enough, not both at the same time): Sometimes it compiles but don't provide the expected result, sometimes it doesn't compile at all.
Even though it seems it isn't practical, I at least want to know when the compilers are faulty, and when I'm writing ill-formed code. Hence this question.
I use the C++11 dialect, and my clang version is actually the compiler provided with XCode 5 i.e. Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn).
To better illustrate what my problem is, here is a minimal exemple where clang compiles but g++ 5.2.1 doesn't:
#include <iostream>
#include <type_traits>
#include <utility>
struct PrivateFoo {
private:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
template<class C, class = void>
struct has_foo : std::false_type {};
template<class C>
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
std::true_type {};
int main() {
std::cout << std::boolalpha;
std::cout << "PrivateFoo has foo: " << has_foo<PrivateFoo>::value << '\n';
return 0;
}
output with clang 3.5:
PrivateFoo has foo: false
g++ 5.2.1 errors:
access_traits.cpp : [in instantiation of] ‘struct has_foo<PrivateFoo>’ :
access_traits.cpp:37:61: required from here
access_traits.cpp:7:8: [error]: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:32:56: [error]: [in context]
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
^
access_traits.cpp:7:8: [error]: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:32:56: [error]: [in context]
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
^
access_traits.cpp: [in function] ‘int main()’:
access_traits.cpp:7:8: erreur: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:37:42: [error]: [in context]
std::cout << "PrivateFoo has foo: " << has_foo<PrivateFoo>::value << '\n';
(text in brackets is translated, it was originally in my native language)
Here is an example where both compile but disagree on whether foo is accessible or not:
#include <iostream>
#include <type_traits>
#include <utility>
struct ProtectedFoo {
protected:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class = void>
struct has_foo_helper : std::false_type {};
template<class C>
struct has_foo_helper<C, void_t<decltype(std::declval<C>().foo())>> :
std::true_type {};
}
template<class C>
struct has_public_or_protected_foo : protected C {
template<class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<has_public_or_protected_foo<C>>::value;
};
int main() {
std::cout << std::boolalpha;
std::cout << "ProtectedFoo has foo: ";
std::cout << has_public_or_protected_foo<ProtectedFoo>::value << '\n';
return 0;
}
output with clang 3.5:
ProtectedFoo has foo: false
output with g++ 5.2.1:
ProtectedFoo has foo: true
and finally here is an example where both compile and agree that they should be able to access foo:
#include <iostream>
#include <type_traits>
#include <utility>
struct ProtectedFoo {
protected:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class D, class = void>
struct has_foo_helper : std::false_type {};
template<class C, class D>
struct has_foo_helper<C, D, void_t<check_signature<void(C::*)(), &D::foo>>> :
std::true_type {};
}
template<class C>
struct has_public_or_protected_foo : protected C {
template<class, class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<C, has_public_or_protected_foo<C>>::value;
};
int main() {
std::cout << std::boolalpha;
std::cout << "ProtectedFoo has foo: ";
std::cout << has_public_or_protected_foo<ProtectedFoo>::value << '\n';
return 0;
}
output with clang 3.5:
ProtectedFoo has foo: true
output with g++ 5.2.1:
ProtectedFoo has foo: true
Also here is a more complete example which summarizes it all:
#include <iostream>
#include <type_traits>
#include <utility>
/* test classes */
struct PublicFoo {
void foo() {}
};
struct ProtectedFoo {
protected:
void foo() {}
};
struct PrivateFoo {
private:
void foo() {}
};
struct NoFoo {};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class D, class = void>
struct has_foo_helper : std::false_type {};
template<class C, class D>
struct has_foo_helper<C, D, void_t<check_signature<void(C::*)(), &D::foo>>> :
std::true_type {};
template<class C, class = void>
struct may_call_foo_helper : std::false_type {};
template<class C>
struct may_call_foo_helper<C, void_t<decltype(std::declval<C>().foo())>> :
std::true_type {};
}
template<class C>
struct has_foo : detail::has_foo_helper<C, C> {};
template<class C>
struct may_call_foo : detail::may_call_foo_helper<C> {};
template<class C>
struct has_protected_foo : protected C {
template<class, class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<C, has_protected_foo<C>>::value;
};
template<class C>
struct may_call_protected_foo : protected C {
template<class, class>
friend class detail::may_call_foo_helper;
static constexpr bool value =
detail::may_call_foo_helper<may_call_protected_foo<C>>::value;
};
/* test */
template<class T>
void print_info(const char* classname) {
std::cout << classname << "...\n";
// comment this if you want to compile with g++
//*
std::cout << "has a public method \"void foo()\": ";
std::cout << has_foo<T>::value << '\n';
std::cout << "has a public or protected method \"void foo()\": ";
std::cout << has_protected_foo<T>::value << '\n';
//*/
std::cout << "has a public method \"foo\" callable without any arguments: ";
std::cout << may_call_foo<T>::value << '\n';
std::cout << "has a public or protected method \"foo\" callable without any "
"arguments: ";
std::cout << may_call_protected_foo<T>::value << '\n';
std::cout << '\n';
}
int main() {
std::cout << std::boolalpha;
// both g++ 5.2.1 and clang 3.5 compile
print_info<PublicFoo>("PublicFoo");
// g++ 5.2.1 fails to compile has_foo, clang 3.5 compiles fine
print_info<ProtectedFoo>("ProtectedFoo");
// g++ 5.2.1 fails to compile, clang 3.5 compiles fine
print_info<PrivateFoo>("PrivateFoo");
// both g++ 5.2.1 and clang 3.5 compile
print_info<NoFoo>("NoFoo");
return 0;
}
Why do I want to do this?
Skip this if you don't want to know the details. I just wrote this in case you were either shocked by the idea of me trying to detect protected members and/or curious about why I asked this question.
I was writing some kind of iterator template classes built out of other iterators and I got tired of writing multiple specializations depending on whether these iterators meet some requirements (ForwardIterator, BidirectionalIterator, RandomAccessIterator... although my iterators actually meet some relaxed versions of these concepts, they are kind of "proxy iterators" but it's not really relevant here).
For instance, if I only use random access iterators, my new custom iterator could (and should) also be some kind of random access iterator, hence implement operator+=, operator+, operator-=, operator-, operator<, operator>, operator<= and operator>=. However, some of these operators can easily be deduced from others, and they should only be defined if all the iterator I use are random access iterators.
I finally thought I'd just make something to provide default implementations if available. However, I wasn't really fond of the std::allocator_traits way as it wouldn't be very handy and readable with iterators (plus, I wouldn't be able to use them with some standard utilities).
The design I finally choose consists in having a template class which will build a full-fledged iterator out of a minimal implementation (for instance containing only the operator+=, operator==, operator* and operator> definitions) by having an inheritance chain of "mixins" (whose ancestor is my minimal iterator) detecting whether the functions/methods they need are available in their base class and defining the default methods if they are.
There is a subtility though. Sometimes I want to return a reference to the final iterator (for instance in Iterator& operator++()). If it's a method I redefine, I can easily solve that with CRTP and a static_cast, but what if my mixins don't touch that method at all?
I figured I should probably forbid the use of any method I haven't touched and inherit my minimal iterator with the protected access specifier... but now then my traits fail to detect the availability of some protected methods.
Therefore, I'd like to have traits able to detect whether some members are available with either public or protected visibility.

boost::lexical_cast with positive sign

How can I make boost::lexical_cast include a positive sign when converting to std::string?
I intend to do the same as: snprintf( someArray, someSize, "My string which needs sign %+d", someDigit );. Here, someDigit would be put in the string as +someDigit if it were positive, or -someDigit if it were negative. See: http://www.cplusplus.com/reference/clibrary/cstdio/snprintf/
How can I make boost::lexical_cast include a positive sign when converting to std::string?
There is no way to control the formatting of built-in types when using boost::lexical_cast<>.
boost::lexical_cast<> uses streams to do the formatting. Hence, one can create a new class and overload operator<< for it and boost::lexical_cast<> will use that overloaded operator to format values of the class:
#include <boost/lexical_cast.hpp>
#include <iomanip>
#include <iostream>
template<class T> struct ShowSign { T value; };
template<class T>
std::ostream& operator<<(std::ostream& s, ShowSign<T> wrapper) {
return s << std::showpos << wrapper.value;
}
template<class T>
inline ShowSign<T> show_sign(T value) {
ShowSign<T> wrapper = { value };
return wrapper;
}
int main() {
std::string a = boost::lexical_cast<std::string>(show_sign(1));
std::cout << a << '\n';
}

How to remove unique_ptr by pointer from a container?

Creating an object and giving ownership to a container using a unique_ptr is no problem. How would one remove an element by raw pointer?
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
You will need to find the iterator corresponding to the myClass element and then pass that iterator to mySet.erase(). The iterator may be found using the std::find_if algorithm with a custom Predicate functor that understands how to dereference unique_ptr and compare it to the raw pointer myClass.
You can not use the overloaded size_t set::erase ( const key_type& x ); since the raw pointer (even if wrapped in a temporary unique_ptr) will not be found in mySet.
Not as pretty as I would've liked. But the following does the job:
#include <memory>
#include <set>
#include <iostream>
struct do_nothing
{
void operator()(const void*) const {}
};
struct MyClass
{
MyClass() {std::cout << "MyClass()\n";}
MyClass(const MyClass&) {std::cout << "MyClass(const MyClass&)\n";}
~MyClass() {std::cout << "~MyClass()\n";}
};
int main()
{
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
std::set<std::unique_ptr<MyClass>>::iterator i =
lower_bound(mySet.begin(), mySet.end(),
std::unique_ptr<MyClass, do_nothing>(myClass));
if (i != mySet.end() && *i == std::unique_ptr<MyClass, do_nothing>(myClass))
mySet.erase(i);
}
It seems i am able to retrieve an iterator using a custom Predicate with lower_bound. Since std::set is an ordered container, lower_bound should perform logarithmically.
std::set<std::unique_ptr<MyClass>>::iterator i =
std::lower_bound(mySet.begin(), mySet.end(), myClass, MyPredicate<MyClass>());
template<class Type>
struct MyPredicate
{
bool operator()(const std::unique_ptr<Type>& left, const Type* right) const
{
return left.get() < right;
}
}
Still not the best solution but for the moment i go with:
PointerMap<MyFoo>::Type myFoos;
MyFoo * myFoo = new MyFoo();
myFoos.insert(PointerMap<MyFoo>::Item(myFoo));
The header is:
#include <map>
#include <memory>
#include <utility>
template<typename T>
struct PointerMap
{
typedef std::map<T *, std::unique_ptr<T>> Type;
struct Item : std::pair<T *, std::unique_ptr<T>>
{
Item(T * pointer)
: std::pair<T *, std::unique_ptr<T>>(pointer, std::unique_ptr<T>(pointer))
{
}
};
};
You might like the answer over here: Efficiently erase a unique_ptr from an unordered_set
That's for C++14, but I think applies to C++11 as well.
It is not pretty, but does the efficient thing — no scanning the container, but using proper hash-based lookup.

Resources