0

I would like to define a staitc member funtion to build my class. This staitc function would access private member, and I make it as friend.

Here is the demo code:

#include <memory>

template<typename T>
class Foo
{
public:
    static std::unique_ptr<Foo> Create();

    friend static std::unique_ptr<Foo> Foo::Create();
};

template<typename T>
std::unique_ptr<Foo<T>> Foo<T>::Create()
{
    return std::unique_ptr<Foo<T>>();
}

template class Foo<int>;
template class Foo<double>;


int main()
{
    return 0;
}

It compiles faild. How to fix it?

foo
  • 398
  • 1
  • 16
  • 1
    Friend functions are by definition free functions, not member ones. A static function is a member function, it doesn't need friendship to access class private section. This looks like an XY-problem. See this question: [How do I call `std::make_shared` on a class with only protected or private constructors?](https://stackoverflow.com/questions/8147027/how-do-i-call-stdmake-shared-on-a-class-with-only-protected-or-private-const) – Evg Nov 26 '20 at 12:01
  • i second Evg, you should rather explain why you think you need `Create` a friend of the class. It isnt possible and you don't need it – 463035818_is_not_an_ai Nov 26 '20 at 12:09
  • static methods have access to private members of the class. – Jarod42 Nov 26 '20 at 12:26

1 Answers1

1

As stated in the comments, you don't need it. Why? Because static member functions are still member functions, meaning they can access private members of the class. I'm assuming that this was the confusion. A small (somewhat contrived) example:

#include <iostream>
#include <memory>

// templated class with private member "data"
template <typename T>
class Foo {
  public:
    // static Create function
    static std::unique_ptr<Foo> Create(T value) {
      auto foo_ptr = std::make_unique<Foo>();

      // can change private members
      foo_ptr->data = value;
      
      return foo_ptr;
    }

    // function to access private member in main
    void printData() {
      std::cout << data << std::endl;
    }

  private:
    T data;
};

int main() {

  auto foo_int = Foo<int>::Create(2);
  foo_int->printData(); // will print 2!

  return 0;
}
Cedric
  • 278
  • 1
  • 9