如何使模板类的模板功能朋友 [英] How to make template function friend of template class

查看:85
本文介绍了如何使模板类的模板功能朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有私有构造函数和析构函数的模板类:

I have a template class with private constructor and destructor:

template <typename T>
class Client
{
    private:
        Client(...) {}
        ~Client()   {}

        template <typename U>
        friend class Client<T>& initialize(...);
};


template <typename T>
Client<T> initialize(...) 
{
      Client<T> client = new Client<T>(...);
}

我不确定朋友的语法是否正确。可以有人帮助吗?

I'm not sure of the correct syntax for the friend. Can anybody help?

推荐答案

忽略椭圆(我假定意味着一堆与问题无关的参数),这应该工作:

Ignoring the ellipses (which I assume mean "a bunch of parameters that aren't relevant to the question"), this should work:

template <typename T>
class Client
{
private:
    Client() {} // Note private constructor
public:
    ~Client() {} // Note public destructor

    // Note friend template function syntax
    template<typename U>
    friend Client<U> initialize();
};


template<typename T>
Client<T> initialize() 
{
      /* ... */
}

请注意,朋友声明与函数声明基本相同,但在返回类型之前加上 friend 关键字。

Notice that the friend declaration is essentially the same as the function declaration but with the friend keyword prefixed before the return type.

此外,析构函数是public的,因此 initialize()的用户将能够破坏 Client< 。构造函数仍然是私有的,所以只有 initialize()才能创建它的实例。

Also, the destructor is public so that users of initialize() will be able to destruct the returned instance of Client<>. The constructor is still private so only initialize() can create instances of it.

工作:

int main()
{
    Client<int> client = initialize<int>();
}

这篇关于如何使模板类的模板功能朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆