仅在头文件中静态模板化成员函数的模板行为

template behavior for static templatized member function in the header file only

本文关键字:函数 成员 文件 静态      更新时间:2023-10-16
class Myclass
{
template <typename T>
static T func()
{
T obj;
return obj;
}
template<>
static int func<int>()
{
}
};

我在上面的类中写了并试图编译它。 我收到以下错误:

错误:

非命名空间范围"类 Myclass">
中的显式专用化错误:主模板声明中的模板 ID "func">

然后我像这样将我的静态函数移到类的一侧:

namespace helper 
{
template <typename T>
static T func()
{
T obj;
return obj;
}
template<>
static int func<int>()
{
}
}
class Myclass
{
template <typename T>
static T func()
{
helper::func<T>();
}
};

我收到以下错误:

错误:显式模板专用化不能在静态成员函数"静态 T Myclass::func(("中具有存储类

然后我当然内联了我的专业功能,它起作用了。

namespace helper 
{
template <typename T>
static T func()
{
T obj;
return obj;
}
template<>
inline int func<int>()
{
return 1;
}
}
class Myclass
{
template <typename T>
static T func()
{
helper::func<T>();
}
};

我的问题是:
1(为什么我们不能在类中专门化静态成员函数.
2(为什么我们不能有静态模板专用函数

老实说,这两个问题的真正答案可能是"因为"。

您可以专用于成员函数模板,它必须位于类之外,并且不能使用static关键字:

struct Myclass {
template <class T>
static T func() {
T obj{};
return obj;
}
};
template <>
int Myclass::func<int>() { return 42; }

两者都主要是语法原因。这只是您必须记住的事情之一。

据我所知,C++不允许在类级别进行成员模板专用化。必须在命名空间级别提供专用化,因此您可以在类外部声明专用化:

// myclass.h
class MyClass
{
public:
template <class T>
void test(T )
{
std::cout << "non-specialized test" << std::endl;
}
template <class T>
static T myfunc()
{
std::cout << "non-specialized myfunc" << std::endl;
return T{};
}
};

template <>
inline void MyClass::test(double t)
{
std::cout << "specialized test" << std::endl;
}
template <>
static double MyClass::myfunc();
/*template <>
static inline void MyClass::myfunc(double )
{
std::cout << "specialized myfunc" << std::endl;
}*/

然后,在源文件中提供实现:

// myclass.cpp
template <>
static double MyClass::myfunc()
{
std::cout << "specialized myfunc" << std::endl;
return 0.0;
}

或者,您可以在头文件中内联myfunc()(就像test()函数一样(。

关于你的第二个问题,我在VS2015中尝试过,它奏效了。唯一的问题是缺少返回值。