Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a variadic template function as a friend?

How to declare a variadic template function as a friend?

For example as follows:

template<class T>
class A
{
    friend ??? MakeA ??? ; // What should be placed here ???

    A(T)
    {}
};

template<class T, class... Args>
A<T> MakeA(Args&&... args)
{
    T t(std::forward<Args>(args));

    return A(t);
}
like image 261
xmllmx Avatar asked Feb 15 '14 03:02

xmllmx


People also ask

What is a templated function?

Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.

Can we declare a template function as the friend of the class?

A template friend declaration can name a member of a class template A, which can be either a member function or a member type (the type must use elaborated-type-specifier).

What is Variadic template in C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

Where to put friend class declaration?

By declaring a function as a friend, all the access permissions are given to the function. The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition.


1 Answers

It's quite straightforward. It's simply a template declaration with the added friend specifier:

template<class T>
class A
{
    template<class T1, class... Args>
    friend A<T1> MakeA(Args&&... args);

    A(T) { }
};
like image 64
David G Avatar answered Sep 22 '22 04:09

David G