I am getting the following compiler error:
/usr/include/boost/variant/variant.hpp:832:32: error: no match for
call to β(const StartsWith) (bool&)β
for the following code. Does anybody know why?
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
using namespace std;
using namespace boost;
typedef variant<bool, int, string, const char*> MyVariant;
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(string &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
int main(int argc, char **argv)
{
MyVariant s1 = "hello world!";
apply_visitor(StartsWith("hel"), s1); // << compiler error
return 0;
}
You have to provide operators for every type declared in MyVariant.
Related
I am unable to compile the following code with gcc 6.4.
gmock version is 1.8.1.
Maybe operator== here looks strange, but I cannot attach the full code due to its size.
#include <iostream>
#include <gmock/gmock.h>
template<class T>
constexpr bool operator==(T&&, T&&) noexcept
{
return true;
}
namespace NNNN
{
struct Param2
{
int i;
};
} // namespace NN
using ::testing::_;
using ::testing::Return;
using ::testing::AtMost;
struct Param
{
int i;
};
struct A
{
MOCK_METHOD1(f, int(const Param&));
};
struct B
{
MOCK_METHOD1(f, int(const NNNN::Param2&));
};
TEST(Test, test)
{
A a;
EXPECT_CALL(a, f(Param{ 1 }));
B b;
std::cout << (NNNN::Param2{ 1 } == NNNN::Param2{ 2 }) << std::endl;
EXPECT_CALL(b, f(NNNN::Param2{ 1 }));
}
int main(int argc, char** argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
The error I get:
In file included from /usr/local/lib/googletest/1.8.1/lib/pkgconfig/../../include/gmock/gmock-spec-builders.h:71:0,
from /usr/local/lib/googletest/1.8.1/lib/pkgconfig/../../include/gmock/gmock-generated-function-mockers.h:44,
from /usr/local/lib/googletest/1.8.1/lib/pkgconfig/../../include/gmock/gmock.h:62,
from /home/jzldfb/projects/uc_workspace/ultracruise/rte/utils/configuration/daemon/sub_module/test/TestApi2.cpp:7:
/usr/local/lib/googletest/1.8.1/lib/pkgconfig/../../include/gmock/gmock-matchers.h: In instantiation of 'bool testing::internal::AnyEq::operator()(const A&, const B&) const [with A = NNNN::Param2; B = NNNN::Param2]':
/usr/local/lib/googletest/1.8.1/lib/pkgconfig/../../include/gmock/gmock-matchers.h:1083:18: required from 'bool testing::internal::ComparisonBase<D, Rhs, Op>::Impl<Lhs>::MatchAndExplain(Lhs, testing::MatchResultListener*) const [with Lhs = const NNNN::Param2&; D = testing::internal::EqMatcher<NNNN::Param2>; Rhs = NNNN::Param2; Op = testing::internal::AnyEq]'
/home/jzldfb/projects/uc_workspace/ultracruise/rte/utils/configuration/daemon/sub_module/test/TestApi2.cpp:60:1: required from here
/usr/local/lib/googletest/1.8.1/lib/pkgconfig/../../include/gmock/gmock-matchers.h:238:60: error: no match for 'operator==' (operand types are 'const NNNN::Param2' and 'const NNNN::Param2')
bool operator()(const A& a, const B& b) const { return a == b; }
If I remove NNNN namespace, the compilation succeeds.
If I add template wrapper for Param2 that calls to template operator== in its operator==, the compilation succeeds.
Thanks for sending me to ADL page.
The solution is to add:
namespace testing {
namespace internal {
using ::operator==;
} }
testing::internal it is a namespace in gmock where operator== is called.
The code above instructs this namespace to look for operator== in global namespace.
I'm trying to create a class that stores pointers to member functions of other classes and that can be executed from a text command (like a game console).
I did something functional, based on an example found here, that stores members with string-like input. Below is my implementation.
file: Command.hpp
#include <string>
#include <functional>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
class Command
{
public:
Command();
virtual ~Command();
void RegisterCommand(string command, function<void(const string&)> fun);
void Run(const string& command, const string& arg);
private:
unordered_map<string, function<void(const string&)>> functions;
};
file: Command.cpp
Command::Command()
{
}
Command::~Command()
{
}
void Command::RegisterCommand(string command, function<void(const string&)> fun)
{
functions[command] = fun;
}
void Command::Run(const string& command, const string& arg)
{
functions[command](arg);
}
file: main.cpp
#include "Command.hpp"
// function to register
void xyz_fun(const string& commandLine)
{
cout << "console output: " << commandLine << endl;
}
int main(int argc, char* argv[])
{
Command m_Cmd;
// Register function
m_Cmd.RegisterCommand("xyz_fun", xyz_fun);
// Run registered function
m_Cmd.Run("xyz_fun", "hello world.");
return EXIT_SUCCESS;
}
My question is how to implement a generic class to store members with unknown input arguments (Booleans, integers, doubles, strings, etc.).
For example, I could do:
m_Cmd.RegisterCommand("xyz_fun2", xyz_function2);
and call
m_Cmd.Run("xyz_fun2", false)
which has a boolean argument instead of a string.
Thanks in advance for your attention and any help is welcome.
Instead of
unordered_map<string, function<void(const string&)>> functions;
you could do
union acceptable_types { int i; char c; bool b; std::string* s; ... };
unordered_map<string, function<void(acceptable_types)>> functions;
Then when calling functions, just place the value wanted by the function into a variable of type acceptable_types.
If a function is wants to use a specific value, it should just use a specific member of the acceptable_types union.
Here's an example:
#include "Command.hpp"
void
my_bool_func (acceptable_types union_param)
{
bool bool_var = union_param.b;
// ...
// Use bool_var
// ...
}
void
my_string_func (acceptable_types union_param)
{
std::string string_var = *(union_param.s);
// ...
// Use string_var
// ...
}
int
main(int argc, char* argv[])
{
Command my_command;
acceptable_types union_var;
my_command.RegisterCommand("my_bool_func", my_bool_func);
my_command.RegisterCommand("my_string_func", my_string_func);
union_var.b = true;
my_command.Run("my_bool_func", union_var);
*(union_var.s) = "hello world.";
my_command.Run("my_string_func", union_var);
return 0;
}
I'm trying to create a map with a custom key, which is an object's pointer address, as mentioned.
I need the address because for now it's the only relevant way to compare between two objects.
from what i understood, the proper way of doing this is by using const char* as key
here is the typedef :
typedef __gnu_cxx::unordered_map<const char*, std::string> TargetsTags;
I'm a bit confused about the following:
how do I create the operator() ?
This is what i used for std::string:
namespace __gnu_cxx {
template<>
struct hash<std::string>
{
hash<const char*> h;
size_t operator()(const std::string &s) const
{
return h(s.c_str());
};
};
}
What about const char*?
And is this the correct way of doing this?
The working example using c++11:
#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>
using namespace std;
class myhash {
public:
size_t operator() (const char *val) const {
return std::hash<std::string>()(val);
}
};
class myequal {
public:
bool operator()(const char *val1, const char *val2) const{
return std::string(val1) == std::string(val2);
}
};
int main() {
std::unordered_map<const char*, string, myhash, myequal> mymap;
mymap["abc"] = "abcd";
mymap["cba"] = "dcba";
std::cout << mymap["abc"] << std::endl;
return 0;
}
The following code won't compile because of "error: no matching function for call to βmem_fun_ref()β" (gcc version 4.4.6).
#include <vector>
#include <string>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
class toto
{
char v[10];
public:
toto(char* t) { memcpy(v, t, 9); }
bool test(const char* var) const { return !strncmp(var, v, 9); }
bool test(const string& var) const { return test(var.c_str()); }
};
int main()
{
vector<toto> t;
t.push_back("1");
t.push_back("2");
string name("2");
vector<toto>::iterator it = remove_if(t.begin(), t.end(),
bind2nd(mem_fun_ref(&toto::test), name)); // <= error
t.erase(it, t.end());
return 0;
}
I found a workaround: creating a
bool testZ(const string& var) const { return testZ(var); }
But I can't seem to find the correct template parameters, if that's even possible, to give to mem_fun_ref (or bind2nd?) to make it compile without my workaround.
Is there anyway to achieve this without my workaround, or is the workaround the "preferred" method?
You should be able to cast it according to C++ overloaded method pointer:
bind2nd(mem_fun_ref((bool (toto::*)(const string&) const) &toto::test), name));
Is it possible to write const function with apply_visitor inside?
For example, this code compiles without errors:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <boost/variant.hpp>
using namespace std;
typedef boost::variant<int,string> vTypeVariants;
struct vType_toN : boost::static_visitor<int>
{
int operator()(int& i) const {
return i;
}
int operator()(const string& str) const{
return str.length();
}
};
class vType{
public:
vType(const int& src) : data(src){}
vType(const std::string& src) : data(src){}
int getLength(){
return boost::apply_visitor(vType_toN(),data);
}
private:
vTypeVariants data;
};
int main(int argc, char ** argv)
{
vType x = string("2");
printf("L=%d",x.getLength());
return(0);
}
Unless you will add const to getLength():
int getLength() const{
return boost::apply_visitor(vType_toN(),data);
}
In such case an error with vast description (2 pages) appears complaining about problem with initializing first argument.
So, the question is: How to use apply_visitor inside const function?
Found out myself.
Forgot const before int in static_visitor class operator definition.
Maybe someone will find this useful as it was not easy to find this out (my original class is much bigger).