为静态模板函数(非成员)提供友谊?

Provide friendship to static template function (non-member)?

这类似于 How to allow template function to have friend(-like) access?,但我使用的是 static 模板函数(非会员)。我正在努力实现以下目标。

Integer.h:

class Integer {    
    ...
    // Forward declare due to static
    template <typename T> static Integer StringToInteger(const T *str, ByteOrder order);
    // Provide friendship
    template <typename T> friend Integer StringToInteger(const T *str, ByteOrder order);
};

Integer.cpp:

// T will be a char or wchar_t
template <class T>
static Integer StringToInteger(const T *str, ByteOrder order)
{
    ...
}

声明友谊时,static 模板函数导致错误:

$ make
c++ -DDEBUG -g3 -O1 -fPIC -Wno-tautological-compare -DCRYPTOPP_DISABLE_ASM -pipe -c integer.cpp

integer.cpp:2970:16: error: static declaration of 'StringToInteger' follows
      non-static declaration
static Integer StringToInteger(const T *str, ByteOrder order)
               ^
./integer.h:380:42: note: previous declaration is here
    template <typename T> friend Integer StringToInteger(const T *str, B...

但是根据Is it possible to declare a friend function as static?,我需要将函数转发声明为static

问题:如何为静态模板函数提供友谊?


如果我将 static 添加到朋友声明中,则会出现另一个错误:

// Forward declaration to retain static
// template <typename T> static Integer StringToInteger(const T *str, ByteOrder order);
template <typename T> friend static Integer StringToInteger(const T *str, ByteOrder order);

然后结果是:

$ make
c++ -DDEBUG -g3 -O1 -fPIC -Wno-tautological-compare -DCRYPTOPP_DISABLE_ASM -pipe -c integer.cpp

In file included from integer.cpp:8:
./integer.h:380:34: error: 'static' is invalid in friend declarations
    template <typename T> friend static Integer StringToInteger(const T ...

如果我尝试在专业上声明友谊:

// Forward declaration to retain static
template <typename T> static Integer StringToInteger(const T *str, ByteOrder order);
friend Integer StringToInteger<char>(const char *str, ByteOrder order);

然后我得到另一个错误:

$ make
c++ -DDEBUG -g3 -O1 -fPIC -Wno-tautological-compare -DCRYPTOPP_DISABLE_ASM -pipe -c integer.cpp

In file included from integer.cpp:8:
./integer.h:381:20: error: no function template matches function template
      specialization 'StringToInteger'
    friend Integer StringToInteger<char>(const char *str, ByteOrder order);

$ c++ --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin12.6.0
Thread model: posix

鉴于 .cpp 中声明的 StringToInteger 是一个自由函数,请在 header 中尝试此操作:

class Integer;

// Forward declare due to static
template <typename T> static Integer StringToInteger(const T *str);

class Integer {    
  public:
  // Provide friendship
  template <typename T> friend Integer StringToInteger(const T *str);
};