[英]Non-member static templated method definitions in C++?
Can I call a non-member static templated function from a static member function where the definition is split into header and cpp: 我可以从静态成员函数调用非成员静态模板化函数,其中定义被拆分为header和cpp:
// zero.cpp
class Zero
{
static void zero() { one(5); }
};
// one.h
template <typename T>
static void one(T& var);
// one.cpp
template <typename T>
void one(T& var) { }
// main.cpp
...
Zero::zero()
...
I'm having problems getting this to link, I keep getting undefined reference to the function I'm trying to define in one.cpp. 我在连接时遇到问题,我一直在尝试在one.cpp中定义函数的未定义引用。
Initially I thought it was due to a problem with namespacing, but all files are now in the same namespace. 最初我认为这是由于命名空间的问题,但所有文件现在都在同一名称空间中。 Am I doing anything fundamentally wrong here?
我在做什么根本上错了吗?
Template definitions need to be visible at the point of instantiation. 模板定义需要在实例化时可见。 That is, it needs to be in the header somehow:
也就是说,它需要以某种方式在标题中:
// one.hpp
template <typename T>
static void one(T& var)
{
// definition visible in header
}
Though I'm not sure why you'd want it to be static. 虽然我不确定你为什么要它是静态的。
As an addition to GMan's answer I would like to note that you can't make T&
bind to an rvalue such as the integral literal 5
which is of type int
. 作为对GMan的回答的补充,我想要注意的是,你不能将
T&
绑定到rvalue,例如int
类型的整数文字5
。 5 will not bind to int&
, but will bind to const int&
. 5将不会绑定到
int&
,但将绑定到const int&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.