2017-07-09 22 views
0

我得到了這樣的事情:如何增加模板類型的int參數?

template<int i> 
struct s {}; 

,我需要這樣寫:

s<1> a = inc<s<0>>; 

我認爲這可能與做:

template<template<int I> typename S> 
using inc = S<I + 1>; 

但它不工作而gcc說模板參數是無效的。

GCC 7,-std = C++ 14

+3

看起來像你想'inc >'來命名一個類型 - 但它然後沒有任何意義上的初始化;預計在那裏表達。你真的想在這裏實現什麼? –

+0

您可能會想到[像這樣](http://rextester.com/LYS30846)。但是,目前還不清楚你打算如何使用它。 –

+0

是的,我想通過編寫'inc >'得到類似於'<0>'的類型,但是'<1>'。 –

回答

0

你方法不能工作,因爲你通過s<0>inc這已經是s一個完整的專業化。

#include <tuple> 
#include <type_traits> 
#include <vector> 

template < int i > 
struct s { 
    constexpr static int value = i; 
}; 

template < typename S > 
struct incrementer; 

template < int i > 
struct incrementer < s<i> > 
{ 
    typedef s<i + 1> type; 
}; 

template < typename S > 
using inc = typename incrementer<S>::type;  

int main() 
{ 
    s<1> a = inc<s<0>>{}; 
} 

與來自問題語法工作(即不用初始化括號),你需要一個variable template from C++17

#include <tuple> 
#include <vector> 

template < int i > 
struct s { 
    constexpr static int value = i; 
}; 

template < typename S > 
struct incrementer; 

template < int i > 
struct incrementer < s<i> > 
{ 
    typedef s<i + 1> type; 
}; 

template < typename S > 
typename incrementer<S>::type inc = typename incrementer<S>::type{};  

int main() 
{ 
    s<1> a = inc<s<0>>; 
}