Restrict friends to templates

Consider the following code:

#include <iostream>

class S {
    static const int i = 42;
    template <class T>
    friend void f();
};

template <class T>
void f()
{
    std::cout << S::i << "\n";
}

int main() 
{
    f<int>();
    f<double>();
}

All I want to do is allow access to the private part of the class Sbefore f<int>, but not for f<double>. That is, I want to get a compiler error, for example 'i' is a private member of 'S'for a string f<double>().

How to achieve this?

+4
source share
2 answers

Creating a template instance - this function, so I just call him void f<int>().

You need a preliminary announcement:

[C++03: 11.4/9 | C++11/C++14: 11.3/11]: (9.8), , , . , , . [..]

( friend -inside-template-declaration, , .)

:

#include <iostream>

template <class T>
void f();

class S {
    static const int i = 42;
    friend void f<int>();
};

template <class T>
void f()
{
    std::cout << S::i << "\n";
}

int main() 
{
    f<int>();
    f<double>();
}

f<double>().

( )

+8

( ) S. , , f<int>(). :

template <class T> void f();

class S {
    static const int i = 42;
    friend void f<int>();
};

template <class T>
void f()
{
    std::cout << S::i << "\n";
}
+2

All Articles