[英]Partial template specialization of non type argument not allowed
以下代碼不起作用,它給出錯誤消息:“ struct foo的模板參數太少”,我不明白為什么。 在我看來,該代碼應該是有效的。 我發現從CPP參考片段這里參見“參數列表”,第4段這或許可以解釋為什么它不工作,但我不明白。
template<int a, int b, int c> struct foo { };
template<int a> struct foo<a, 0, 0> { };
int main()
{
foo<1> f;
}
允許 但是您的模板需要3個參數。 專門化它不會神奇地將其變成1參數模板。
您可以使其他參數具有默認參數,但是:
template<int a, int b = 0, int c = 0> struct foo { char _[1] ; };
template<int a> struct foo<a, 0, 0> { char _[10] ;};
int main() {
static_assert(sizeof(foo<1>) > sizeof(foo<1, 1, 1>), "");
return 0;
}
請注意,主模板具有3個模板參數。 然后,您必須指定所有這些。 例如
foo<1, 0, 0> f; // the partial specification is used
模板專業化不是這樣工作的。 您必須*指定所有參數。
*(除非您具有默認參數 (請參見@StoryTeller的答案),或者當C ++ 17參數推演生效時,但兩者均不適用於此處。)
這是一個小演示:
#include <iostream>
template<int a, int b, int c> struct foo { void bar() {std::cout << "1\n";} };
template<int a> struct foo<a, 0, 0> { void bar() {std::cout << "2\n";} };
int main()
{
foo<1, 2, 3> a;
foo<4, 0, 0> b;
a.bar(); // prints 1
b.bar(); // prints 2
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.