1

假设我有

template<class T>
void f(T t);

template<class T>
class X
{   
};

如果我只想f<T>成为 的朋友X<T>,我声明:

template<class T>
class X
{
    friend void f<>(T t);
};

现在假设 f 声明如下:

template<class T, class U>
void f(T t, U u);

我想声明以下内容:对于任何类型U f<T, U>都是X<T>. 所以我想f<int, char>成为的朋友X<int>,但我不想f<char, int>成为朋友X<int>。这可能吗?以下似乎无法编译

template<class T>
class X
{
    template <class U>  
    friend void f<>(T t, U, u);
};

请注意,我知道如何将整个模板声明为朋友。

4

2 回答 2

0

显然,当前的 C++ 没有办法做我所追求的。

于 2014-12-13T12:33:04.670 回答
-2

[EDIT] I had taken this idea from a website which stated this was possible, but not properly tested it. As it turns out, this does not work, so please disregard this suggestion.

As far as I can tell, what OP wants to do is not possible in c++... [/EDIT]

The code as you posted it would partially specialize the function f, however this is not allowed.

To fix it, remove the empty angle brackets from the friend declaration:

template<class T>
class X
{
    template <class U>  
    friend void f(T t, U, u);
};
于 2013-08-08T15:39:47.940 回答