C ++ syntax question including non-trivial templates and friend declaration

The following code should be clear. I have two questions regarding the syntax used (which is the syntax that should be used). I will be forever grateful if you can provide me with answers to these questions.

template <typename T>
struct A {
    template <typename S>
    void f (const A<S> &s);

    template <typename S>
    friend struct A; 
    // Question 1: why isn't the syntax 'friend struct A<S>' ? 
    // The semantic would stay, since we would like A<S> (for ANY S) to be friend of every A<T>..

    private:
        void g () const {}
};

template <typename T> 
template <typename S> // Question 2: Why can't the syntax be 'template <typename T, typename S>' ?
void A<T>::f (const A<S> &s) {
    s.g();
}

int main () {
    A<bool> abool;
    A<char> achar;

    abool.f(achar);
}

I checked that this is actually the only correct syntax (I will be glad to know that I am wrong). My questions are more about substantiating syntax, as explained in the body of the questions.

Thanks for any help.

+3
source share
3 answers

why not the syntax ...

Why the syntax cannot be ...

? , ( , AFAIK), , , .

, , , . , .

: , №2. # 1:

, A<S> , , A , , , :

template <typename S>
void f (const A<S> &s); // A<S> being the name of a type

template <typename S>
friend struct A; // A being the name of a template

, (.. ) friend:

template< typename T >
class foo;

class bar {
  friend class foo<int>; // foo<int> being the name of a specific instance of foo
};

( "" friend ) .

+5

, , , , - . 2 , . ? , , template<>.

+5

, :

template <typename T, int I>
struct A {
    template <typename S, I>
    void f (const A<S, I> &s);

    template <typename S, int J>
    friend struct A; 
    // Question 1: why isn't the syntax 'friend struct A<S, J>' ? 
    // The semantic would stay, since we would like A<S, J> (for ANY S, J combination) to be friend of every A<T, I>..

    private:
        void g () const {}
};

template <typename T, int I> 
template <typename S> // Question 2: Why can't the syntax be 'template <typename T, int I, typename S>' ?
void A<T>::f (const A<S> &s) {
    s.g();
}

int main () {
    A<bool, 5> abool;
    A<char, 7> achar;

    abool.f(achar);
}

. ? , ++ 0x ?

, (friend struct <S, J>), , S J - . , - S , struct A? S friend struct A<S,J>? ? , ?

, , : template <typename S, int J> friend struct A<S, J>, , ? , , template <typename S, int J>.

, , , .

, A :

template <typename T>
struct A<T, 5> {
};

, , , , . , , , , .

+2

Source: https://habr.com/ru/post/1730780/


All Articles