[英]how to define a C++ method outside the declaration for a variadic templated class specialized to no parameters?
[英]How to specialized a variadic argument method defined inside a variadic templated class?
我有一個可變參數模板 class,其中包含一個可變參數 arguments 的方法。 我想根據 class 的專用版本提供的一些參數對方法進行專門化。
我知道如何專門化可變參數函數以及如何執行模板專門化。 不幸的是,我沒有設法同時使用這兩個專業。
我當前的解決方案似乎覆蓋了我不想要的解決方案。 下面是簡化的問題
#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;
}
如何在上面的示例中實現“價值”方法的專業化?
只能有一個Foo<X,Y>
類型。
正因為如此,您不能根據其函數之一的模板參數專門化Foo
本身。 想一想:如果Foo
里面有多個模板函數會發生什么?
但是,您可以通過重載function本身而不是類型來創建 function 的專用版本,就像您要求的那樣:
template<>
template<>
int Foo<X, Y>::value(int a, int b) {
return 12;
}
int test() {
return Foo<X,Y>::value(1,2);
}
這與模板或專業化無關。 很簡單,真的:
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.