S
S
sanek20052021-07-13 17:53:48
C++ / C#
sanek2005, 2021-07-13 17:53:48

Is it possible to make a template function friend of a class?

In general, I have a class. it has certain fields. one object of this class is a global variable. and so it turned out that two template functions need to access the fields of this object directly. I do not want to make fields public, encapsulation is violated. and only these two templates are accessed outside the class. is it possible to make template functions members of a class - I don’t know, and they shouldn’t be them logically

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2021-07-13
@sanek2005

#include <iostream>

class Wrap
{
public:
    Wrap(int x) : value(x) {}
private:
    int value;

    template <class T>
    friend void out(const T&);
};

template <>
void out(const Wrap& x)
    { std::cout << x.value << std::endl; }

int main()
{
    Wrap x(42);
    out(x);
    return 0;
}

If needed in a namespace...
spoiler
#include <iostream>

namespace qq {
    template <class T>
    void out(const T&);
}

class Wrap
{
public:
    Wrap(int x) : value(x) {}
private:
    int value;

    template <class T>
    friend void qq::out(const T&);
};

template <>
void qq::out(const Wrap& x)
    { std::cout << x.value << std::endl; }

int main()
{
    Wrap x(42);
    qq::out(x);
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question