2013-04-30 50 views
0

根據我以前的文章,我瞭解到我不能使用函數參數作爲編譯時構造的參數。這是因爲函數的參數預計在運行時,但模板參數在編譯時間處理。如何避免爲採用編譯時間值的操作符編寫顯式模板參數?

因爲我很遺憾不能在參數中使用constexpr,我決定使用模板參數。它工作正常,但相對於長相我不會說這是最好的選擇:

#include <tuple> 

template <class... Args> 
struct type_list 
{ 
    std::tuple<Args...> var; 

    type_list(Args&&... args) : var(std::forward<Args>(args)...) {} 

    template <std::size_t N> 
    auto operator[](std::size_t) 
     -> typename std::tuple_element<N, std::tuple<Args...>>::type&& 
    { 
     return std::move(std::get<N>(var)); 
    } 
}; 

int main() 
{ 
    type_list<int, int, bool> list(2, 4, true); 

    int i = list.operator[]<0>(0); // How can I avoid this? 
} 

有一些方法可以讓我避免這種情況?如何避免顯式的操作符語法,如何給函數一個常量表達式?宏可以用嗎?

+1

是:

template <typename T> auto operator[](T) -> ... 

運營商裏面有T,如果你使用boost MPL

使用的運營商更改此代替n ::值有直接使用元組和'std :: get'有問題嗎? – 2013-04-30 02:57:25

回答