Answer the question
In order to leave comments, you need to log in
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
#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;
}
#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 questionAsk a Question
731 491 924 answers to any question