[英]How do I specialize this template member function?
I have this setup: 我有这个设置:
class DontUse;
template<class T,class U = DontUse, class V = SomeStandardType>
class Foo
{
public:
void bar(U &uh);
};
When U is set to DontUse, I want bar to be an empty function. 当U设置为DontUse时,我希望bar为空函数。 In all other cases, I want bar to have some implementation.
在所有其他情况下,我希望bar有一些实现。 I tried doing this using specialization, but this code (which I realize is somehow incorrect) doesn't compile:
我尝试使用专门化,但这个代码(我意识到在某种程度上是不正确的)不编译:
template<class T,class V> void Foo<T,DontUse,V>::bar(DontUse &none){}
template<class T,class U,class V> void Foo<T,U,V>::bar(U &uh)
{
//do something here
}
The error message is this (MSVC10): 错误消息是这个(MSVC10):
1>path_to_project: error C2244: 'Foo<T,U,V>::bar' : unable to match function definition to an existing declaration
and it points to the line of the first template specialization. 它指向第一个模板专业化的行。
How do I do this correctly? 我该怎么做呢?
Here's the actual code, although it's reduced to the minimalist part that's relevant: 这是实际的代码,虽然它已经简化为相关的极简主义部分:
struct DontUse;
template<typename Derived, typename Renderer = DontUse, typename TimeType = long>
class Gamestate
{
public:
void Render(Renderer &r);
};
template<typename Derived, typename TimeType> void Gamestate<Derived, DontUse,TimeType>::Render( DontUse){}
template<typename Derived, typename Renderer, typename TimeType> void Gamestate<Derived,Renderer,TimeType>::Render(Renderer &r)
{
static_cast<Derived*>(this)->Render(r);
}
You cannot specialize individual members of a template. 您无法专门化模板的各个成员。 You have to specialize the class itself:
你必须专门化这个类本身:
class DontUse;
template<class T, class V>
class Foo<T, DontUse, V>
{
public:
void bar(DontUse)
{ }
};
I recommend to just use this: 我建议只使用这个:
#include <type_traits>
template <class A, class B, class C>
struct S
{
void foo(B& b)
{
static_assert(!std::is_same<U, DontUse>::value, "Bad Boy!");
}
};
Or, if you really want a empty function, just use an if. 或者,如果你真的想要一个空函数,只需使用if。
#include <type_traits>
template <class A, class B, class C>
struct S
{
void foo(B& b)
{
if(!std::is_same<U, DontUse>::value)
{
//all code goes here
}
}
};
It doesn't work like that. 它不像那样工作。 A member function of a class template is not itself a separate template, and cannot be specialized (partially or fully) independently of the class template.
类模板的成员函数本身不是一个单独的模板,并且不能独立于类模板进行专门(部分或完全)。
You need to define a partial specialization of the class template Foo
, give it a bar
member function, and define that. 您需要定义类模板
Foo
,给它一个bar
成员函数,并定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.