内部に配列を含む型があります。タイプがAでない場合は、Aまたは1の配列メンバーの数を返す関数が必要です。
コードは次のとおりです。
#include <cstdio>
template<typename T, unsigned n>
struct A
{
T values[n];
};
template<typename T>
unsigned count_components()
{
return 1;//all types except 'A' should have 1 component
}
template<typename T, unsigned n>
unsigned count_components<A<T, n> >()//specialize count_components for 'A'
{
return n;
}
int main()
{
printf("%d\n", count_components<A<float, 4> >());//should be 4
printf("%d\n", count_components<float>());//should be 1
return 0;
}
G ++エラー:
test.cpp:13:37: error: function template partial specialization ”count_components<A<T, n> >” is not allowed
unsigned count_components<A<T, n> >()//specialize count_components for 'A'
^
私が関数を持っているとき、私は関数を使い続けることを好みます(あなたはまだアクセスできるので、これはメンバー関数でより有益です*this
)。
template<typename T, unsigned n>
unsigned count_components_switch(boost::mpl::identity<A<T, n>>)
{
return n;
}
template<typename T>
unsigned count_components_switch(boost::mpl::identity<T>)
{
return 1;
}
template<typename T>
unsigned count_components()
{
return (count_components_switch)(boost::mpl::identity<T>());
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加