2016-06-28 46 views
7

模板非常適合編程模板函數和類,所以我們可以用它來縮短代碼並讓編譯器爲我們做一些工作。可變模板和無值

在我的情況下,我想利用模板類例如。

template <typename T, typename G> class unicorn { 
T value01; 
G value02; <- not used in ever instance of class unicorn 
}; 

有一種方法,編譯器作出與類型名稱T = INT例如和一個實例,如果不使用或指定版本無類型名G&

這樣的結果是這樣的:

unicorn <double, int>; 

class unicorn { 
double value01; 
int value02; 
}; 

而且沒有參數或指定的類型名稱摹

unicorn <double> 

class unicorn { 
T value01; 
// "not included in this instance" 
}; 
+0

一種類型的單獨模板或可能是模板和std ::元組? – KIIV

+0

看來你正在嘗試重新發明'std :: tuple',注意你不想要兩個以上的模板參數。 –

回答

5

如果你有使用案例的數量有限,不想潛入深模板元編程,然後你可以簡單地做模板專業化

#include <iostream> 
using namespace std; 

template <typename... Args> 
struct Something; 

template <typename T> 
struct Something<T> { 
    T a; 
}; 

template <typename T, typename U> 
struct Something<T, U> { 
    T a; 
    U b; 
}; 

int main() { 
    __attribute__((unused)) Something<int> a; 
    __attribute__((unused)) Something<int, double> b; 

    return 0; 
} 

但是對於一般情況下,我認爲std::tuple可能會在這裏做到這一點。看看下面的代碼

#include <tuple> 
#include <iostream> 
using namespace std; 

template <typename... Args> 
class Something { 
    std::tuple<Args...> tup; 
}; 

int main() { 
    __attribute__((unused)) Something<int> a; 
    __attribute__((unused)) Something<int, double> b; 

    return 0; 
} 

當然,你應該知道的像std::ref一些事情,並記錄進行get<>功能。您還可以使用某些模板元編程訪問模板包的類型。我不是在這裏解釋,因爲它可能會成爲一個真的長的答案,否則,如果你仍然希望我這樣做,請讓我知道在下面的評論,我會盡力向你解釋。

+0

你應該嘗試使專業化通用。 – user2296177

+0

@ user2296177對不起,我不認爲我遵循,你是什麼意思? – Curious

+0

不專注於''和'',專門爲''和''。例子:這兩種類型專精是'template struct Something {T a; U b; };' – user2296177