[英]How to specialized a variadic argument method defined inside a variadic templated class?
I have a variadic templated class which contains a method with variadic arguments.我有一个可变参数模板 class,其中包含一个可变参数 arguments 的方法。 I would like to specialize the method depending on some of the parameters provided with a specialized version of the class.
我想根据 class 的专用版本提供的一些参数对方法进行专门化。
I know how to specialize variadic argument functions and how to perform template specialization.我知道如何专门化可变参数函数以及如何执行模板专门化。 Unfortunately, I have not managed to use both specializations together.
不幸的是,我没有设法同时使用这两个专业。
My current solution seems to be overriding the solution which is not what I want.我当前的解决方案似乎覆盖了我不想要的解决方案。 Below is the simplified problem
下面是简化的问题
#include <iostream>
struct X;
struct Y;
template<typename ... FooTs>
struct Foo
{
public:
template < typename... Ts >
static int value(Ts... args){ return 0;};
};
template <>
struct Foo<X,Y>{
static int value(int& a, int& b, float& c)
{
std::cout << "specialized value 3 args..." << std::endl;
return 0;
}
};
/* Ideally I would also like to have such specialization
template <>
struct Foo<X,Y>{
int value(int a, int b)
{
std::cout << "specialized value 2 args..." << std::endl;
return 0;
}
};*/
int main(){
Foo<X, Y> foo;
int a = 1;
int b = 2;
float c = 3.4;
Foo<X,Y>::value(a, b, c);
foo.value(a, b, c);
// foo.value(a, b); // error: no matching function for call to 'Foo<X, Y>::value(int&, int&)
return 0;
}
How can I achieve the specialization of the "value" method on the example above?如何在上面的示例中实现“价值”方法的专业化?
There can only be be single Foo<X,Y>
type.只能有一个
Foo<X,Y>
类型。
Because of this, you cannot specialize Foo
itself based on the template parameters of one of its functions.正因为如此,您不能根据其函数之一的模板参数专门化
Foo
本身。 Think about it: What would happen if Foo
had multiple templated functions inside of it?想一想:如果
Foo
里面有多个模板函数会发生什么?
However, you can create a specialized version of the function like you are asking by overloading the function itself instead of the type:但是,您可以通过重载function本身而不是类型来创建 function 的专用版本,就像您要求的那样:
template<>
template<>
int Foo<X, Y>::value(int a, int b) {
return 12;
}
int test() {
return Foo<X,Y>::value(1,2);
}
This has little to do with templates, or specialization.这与模板或专业化无关。 It's simple, really:
很简单,真的:
template <>
struct Foo<X,Y>{
static int value(int& a, int& b, float& c)
{
std::cout << "specialized value 3 args..." << std::endl;
return 0;
}
int value(int a, int b)
{
std::cout << "specialized value 2 args..." << std::endl;
return 0;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.