Boost logo

Boost Users :

Subject: Re: [Boost-users] function template with a universal reference to a specific type
From: degski (degski_at_[hidden])
Date: 2018-12-31 06:09:53

On Sun, 30 Dec 2018 at 17:05, Ireneusz Szcześniak via Boost-users <
boost-users_at_[hidden]> wrote:

> I'm writing to ask a C++ question, not specifically Boost-related, but
> this list is the best place I know.

A better place would be [relatively
informal] or [more formal, requirement for good
formulation of your problem].

How can I write a function template, which has a parameter of the
> universal reference to a specific type?
> I can write a function template like this:
> template <typename T>
> void
> foo(T &&t)
> {
> // The primary template implementation.
> cout << "Primary: " << __PRETTY_FUNCTION__ << endl;
> }

You have to read up on universal references [] as in the above a UR
seems in-appropriate, as printing in general should [normally] not involve
"consuming" [i.e. move] the value your printing. It's saves typing but
"using namespace std;" will, once you get bigger projects, give you
[potentially] grief, it's advisable to just type std:: everywhere. If there
are really long [and several nested namespaces] you can just write a
short-cut, like so

namespace fs = std::filesystem;

And so I can call this function with an expression of any value
> category, and any type, cv-qualified or not, like this:
> int
> main()
> {
> foo(1);
> int i = 1;
> foo(i);
> const int ci = 1;
> foo(ci);
> }
> In my code I need to provide different implementations of foo for
> different types (and these types are templated). How can I accomplish
> that?

You can simply overload the <<-operator for the types you need.

Like [just copied some code as an example]:

template<typename Stream>
[[ maybe_unused ]] Stream & operator << ( Stream & out_, const point2f & p_
) noexcept {
    out_ << '<' << p_.x << ' ' << p_.y << '>';
    return out_;

after which you can just write:

point2f p { 1.2f, 5.6f };
std::cout << p << '\n';

The nice thing [of the above] is that it [your overload] will also work
with other stream-types [].


*“If something cannot go on forever, it will stop" - Herbert Stein*

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at