如何使静态模板成员函数成为友元
How to make a static template member function as friend
我想定义一个 static 成员函数来构建我的 class。这个staitc函数会访问私有成员,我把它加为好友。
这里是演示代码:
#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;
}
编译失败。如何解决?
如评论中所述,您不需要它。为什么?因为静态成员函数仍然是成员函数,这意味着它们可以访问 class 的私有成员。我假设这是混乱。一个小的(有点做作的)例子:
#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;
}
我想定义一个 static 成员函数来构建我的 class。这个staitc函数会访问私有成员,我把它加为好友。
这里是演示代码:
#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;
}
编译失败。如何解决?
如评论中所述,您不需要它。为什么?因为静态成员函数仍然是成员函数,这意味着它们可以访问 class 的私有成员。我假设这是混乱。一个小的(有点做作的)例子:
#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;
}