仅在头文件中静态模板化成员函数的模板行为
template behavior for static templatized member function in the header file only
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中尝试过,它奏效了。唯一的问题是缺少返回值。
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针