Class-Wide `using` alias as return type issuing compiler error - c++11

In order to keep some code readable and avoid typos, I'm using the following statement in the public section of a class definition in a header file:
using Assembly_Tuple = std::tuple <std::vector <std::string>, Trigger_Map, Attribute_Map>;
I'm declaring a function in the header file with Assembly_Tuple as a return type:
Assembly_Tuple merge_node_attributes(const std::string& node_name, std::string tmpl_name="");
And I'm defining the function in the source file:
Widget_Server_Interface::Assembly_Tuple
Widget_Server_Interface::merge_node_attributes(const std::string& n, const std::string& t)
{
//...
}
But when I try to compile, I get the following error:
src/WidgetServer/WidgetServerInterface.cpp:31:1: error: ‘Assembly_Tuple’ in ‘class Widget_Server_Interface’ does not name a type
However, inside definitions, there aren't any problems.
If I change that line to the egregious:
std::tuple<std::vector<std::string>, Trigger_Map, std::map<int,Node_Value>>
Widget_Server_Interface::merge_node_attributes (...) {...}
it's fine. Clearly the problem is using the alias outside of scope, even though it's public
and I'm explicitly calling on the class namespace.
I looked in Bjarne's book but he doesn't mention anywhere whether or not this is legal.
This is using gcc 4.7.
Mostly, I would just like to know why this isn't valid.

Related

how to use pointer of one namespace in another namespace nad both the namespace are used in another class

Below is my sample code where we are facing the issue
file1.h
namespace name1
{
extern name1::test* _test;
}
file2.h
namespace name2
{
class toolbox
{
int fun()
{
return _test->test();
}
}
}
newfile.cpp
using namespace name1;
using namespace name2;
int newclass::new()
{
return _test->test();
}
With above I will get error :
undefined reference to name2::_test
If I add extern in name2 I get error :
_test ambiguous
The problem you have are conflicting symbols between the namespaces that you are using.
This is a typical example used in styleguides which forbid using namespace.
Instead of including the whole namespace, you could prefix the identifiers with NS::, for example: name1::_test.
Alternatively, it is possible to selectively use elements from the namespace by using: using NS::Identifier. However, I never found myself in a situation where I needed on a global, so don't know if this works.
A piece of advice: don't use global variables, it is much more maintainable to pass the pointers or references as arguments for your functions.

How I can use std::bind to bind class member function as function pointer?

I have Base and Dervided classes. In the Base class I have a typedef for specific function pointer (I think this is function pointer, im not sure):
typedef void (responseHandler)(BaseClass* instance,int resultCode, char* resultString);
And in the same base class I have several functions which accepts this typedef:
unsigned sendDescribeCommand(responseHandler* responseHandler, Authenticator* authenticator = NULL);
In my custom derived class from this Base class I have my response handler function, like this:
void continueAfterDESCRIBE(RTSPClient* rtspClient, int resultCode, char* resultString);
How I can use this method as input for sendDescribeCommand?
I tried this:
DerivedClass->sendDescribeCommand(DerivedCLass->continueAfterDescribe, MyAuth), but this did not build with error:
"error C3867: 'DerivedClass::continueAfterDESCRIBE': non-standard syntax; use '&' to create a pointer to member"
I also tried to use std::bind:
auto responseCallback = std::bind(&DerivedClass::continueAfterDESCRIBE, DerivedClassInstance);
DerivedClass->sendDescribeCommand(responseCallback, ourAuthenticator);
It also give me an error: no suitable conversion from std::bind to my response handler.
I know there is a way to make my method static, but Im curious if there is another way?

Two step constructions for enable_shared_from_this object that needs to pass std::shared_ptr<self> to children created in constructor

I know that additional initialization methods are evil, as they leave a very nasty option for having object half-constructed and as result all methods needs to check for this. But what about this situation?
class config;
class cfg_item final
{
private:
friend class config;
cfg_item(std::weak_ptr<config> owner) : owner(owner) { }
std::weak_ptr<config> owner;
}
class config final : private std::enable_shared_from_this<config>
{
public:
config()
{
items.emplace(std::make_shared<cfg_item>(weak_from_this())); // Will crash!
}
private:
std::vector<std::shared_ptr<cfg_item>> items;
}
int main(int argc, char * argv[])
{
std::shared_ptr<config> cfg = std::make_shared<config>();
}
I KNOW WHY IT CRASHES. The std::shared_ptr in the main is not yet initialized with shared pointer to config instance, so constructor does not know how to make weak_from_this and just raises std::bad_weak_ptr exception because there are no valid std::shared_ptr pointing to this at constructor's call time.
The question is: how can I avoided the whole thing? I believe the only way I see would be to add separate initialization method, which is evil as I've already mentioned...
As note about real code: the constructors loads cfg_item from external source. It is assumed that all cfg_items are available for the entire lifetime of config. The weak pointers back to config are mandatory, as cfg_item must push all changes done to it back to config to save to external source
If you look at the answers to this question, there are strong arguments why an external initialization function is necessary. However, you rightfully write
I know that additional initialization methods are evil, as they leave a very nasty option for having object half-constructed and as result all methods needs to check for this.
it's possible to reduce this problem. Say you have a class foo, with the protocol that each time a foo object is constructed, foo::init() needs to be called. Obviously, this is a brittle class (client code will eventually omit calls to init()).
So, one way is to make the (non-copy / non-move) constructors of foo private, and create a variadic static factory method that creates objects, then calls init():
#include <utility>
class foo {
private:
foo() {}
foo(int) {}
void init() {}
public:
template<typename ...Args>
static foo create(Args &&...args) {
foo f{std::forward<Args>(args)...};
f.init();
return f;
}
};
In the following code
template<typename ...Args>
static foo create(Args &&...args) {
foo f{std::forward<Args>(args)...};
f.init();
return f;
}
note that this single method can be used for all constructors, regardless of their signature. Furthermore, since it is static, it is external to the constructor, and doesn't have the problems in your question.
You can use it as follows:
int main() {
auto f0 = foo::create();
auto f1 = foo::create(2);
// Next line doesn't compile if uncommented
// foo f2;
}
Note that it's impossible to create an object without this method, and the interface doesn't even contain init.

std::unique_ptr declared on base class

Sorry about the title, I couldn't come with a better one.
Suppose that I have a class with special delete semantics, which needs to call a function instead of been deleted by delete, let's call it releaseable_object:
struct releaseable_object
{
releaseable_object() : dummy_ptr(new int) {}
void Release()
{
std::cout << "Releasing releaseable object\n";
delete dummy_ptr;
}
int *const dummy_ptr;
};
And this releaseable_object is the base class of a bunch of other objects, each of them constructed by a factory which only returns pointers.
I'm trying to wrap each class into a std::unique_ptr with a custom deleter which call the releaseable_object::Release() function, so I've created a helper struct to handle some of the generic stuff:
// std::is_base_of<releaseable_object, T>::value must be true
template <typename T> struct Managed
{
using type = T;
static void deleter(type *object)
{
std::cout << "Release!\n";
object->Release();
};
using pointer = std::unique_ptr<T, decltype(deleter)>;
};
And then, a bunch of derived classes which does all the specific initializations and calls to te factory:
struct ManagedA : Managed<A>
{
using base = Managed<A>;
using base::pointer;
using base::deleter;
ManagedA(/* lots of parameters */) :
m_pointer(nullptr, deleter)
{
// do A specific stuff...
A *a = factory::CreateA(/* lots of parameters */);
// more A specific stuff...
// wrap the pointer:
m_pointer.reset(a);
}
pointer m_pointer;
};
If I try to compile the code above, it complains about the unique_ptr (demo here), I don't know what I'm doing wrong there, the error is about the instantiation of a tuple (the complete error log is in the ideone demo):
tuple: In instantiation of ‘struct std::_Head_base<1u, void(A*), false>’:
tuple:229:12: recursively required from ‘struct std::_Tuple_impl<1u, void(A*)>’
tuple:229:12: required from ‘struct std::_Tuple_impl<0u, A*, void(A*)>’
tuple:521:11: required from ‘class std::tuple<A*, void(A*)>’
bits/unique_ptr.h:127:57: required from ‘class std::unique_ptr<A, void(A*)>’
If I get rid of the m_pointer member then the compilation succeeds. I'm pretty lost with this, I'll be grateful of any hints about how to fix the compilation error.
Thanks for your attention.
The problem is that decltype(deleter) is a function type instead of a pointer-to-function type. Changing the pointer declaration to
using pointer = std::unique_ptr<T, decltype(deleter)*>; // or spell out void(*)(T*)
will fix it.
Be aware that a function object type is usually preferable to a function pointer type for a unique pointer deleter, since the function pointer must be stored in the object itself. i.e.,
sizeof(std::unique_ptr<foo*,void(*)(foo*)>) == sizeof(foo*) + sizeof(void(*)(foo*))
but most implementations will take advantage of the Empty Base Optimization if you use an empty deleter type:
struct deleter_type {
void operator () (foo*) {
// ...
}
};
sizeof(std::unique_ptr<foo*,deleter_type>) == sizeof(foo*)
Here's how your sample code would be written using a deleter type..

is it possible to have boost::optional of a class and call its member functions?

I tried using boost optional and it works nice, but I cant find a way to call the member functions of the wrapped type. Is that by design or? I guess so because calling member funcs of unitialized boost::optional variable would be bad, but I want to be 100% sure.
class test
{
int test_method()
{
return 1984;
}
};
test tst;
boost::optional<test> get_test()
{
boost::optional<test> result(tst);
return result;
}
// main
boost::optional <test> ret_val= get_test();
int x=ret_val.test_method();
‘class boost::optional ANGLE_BRACKET test ANGLE_BRACKET ’ has no member named ‘test_method’
Try using ret_val->test_method() instead; operator-> can access the contained object in a boost::optional. Note that you need to ensure that the optional is not empty before you do that.

Resources