Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wrap a function (std::bind) into a namespaces?

Tags:

c++

bind

wrapper

I want to wrap the bind class template into an separate namespace:

namespace my_space {
template<typename... R> using bind = std::bind<R...>;
}

and get an error:

error: 'bind<R ...>' in namespace 'std' does not name a type.

How am i able to do so? A small example can be found here.

like image 638
user1810087 Avatar asked Dec 12 '22 05:12

user1810087


2 Answers

Why your code does not work

Your code doesn't compile because std::bind is a function, not a type. You can declare aliases using using only for types.

While g++ diagnostic is not exactly the best, Clang++ would have given you the following error:

error: expected a type

which is much clearer*.

What you can do

Thankfully you can just import the std::bind name using:

namespace my_space {
    using std::bind;
}

Live demo

This is specifically defined in:

§7.3.3/1 The using declaration [namespace.alias]

A using-declaration introduces a name into the declarative region in which the using-declaration appears.

* Personal opinion.

like image 89
Shoe Avatar answered Dec 22 '22 04:12

Shoe


I don't know if you can get that to work with using, but an alternative might be wrapping via perfect-forwarding. Any good compiler would optimize the wrapper away.

namespace my_space {
    template<class... Args>
    auto bind(Args&&... args) -> decltype( std::bind(std::forward<Args>(args)...) )
    {
        return std::bind(std::forward<Args>(args)...);
    }
}

In C++14 you can even drop the -> decltype( std::bind(std::forward<Args>(args)...) ) part.

A working example can be found here

like image 45
KillianDS Avatar answered Dec 22 '22 03:12

KillianDS