簡體   English   中英

g ++可變參數模板。 簡單的示例代碼無法編譯,抱怨'不是模板'

[英]g++ variadic templates. Simple Sample code won't compile, complains 'Not a template'

我在這個陌生的領域徘徊,並且我想從Danny Kalev關於此事的教程中嘗試一個簡單的例子。 代碼非常簡單:

template<> struct Count<> { static const int value = 0;};

template<typename T, typename... Args>
    struct Count<T, Args...> //partial specialization
{ 
    static const int value = 1 + Count<Args...>::value;
};

但gcc 4.4.7甚至4.7.0抱怨(盡管-std = c ++ 0x -std = gnu ++ 0x flags):

/src/tests/VTemplates.h:12:8: error: 'Count' is not a template
/src/tests/VTemplates.h:12:18: error: explicit specialization of non-template 'Count'
/src/tests/VTemplates.h:16:8: error: 'Count' is not a template
/src/tests/VTemplates.h:16:26: error: 'Count' is not a template type

我錯過了什么?

template<> struct Count<> { static const int value = 0;};

是沒有模板參數的模板特化。 但是你不能專門化一個不是非專業模板的模板類。 換句話說,您必須首先建立模板類的非專業版本,然后才能將其專門化。 例如,如果您這樣做:

//non-specialized template
template<typename... Args>
struct Count;

//specialized version with no arguments
template<> struct Count<> { static const int value = 0;};

//another partial specialization
template<typename T, typename... Args>
struct Count<T, Args...> 
{ 
    static const int value = 1 + Count<Args...>::value;
};

那會有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM