这类似于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
答案 0 :(得分:1)
鉴于.cpp中声明的StringToInteger是一个自由函数,请在标题中尝试:
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);
};