繁体   English   中英

需要额外模板参数的类型的函数的部分模板专业化

[英]Partial template specialization of a function for a type which needs additional template parameters

我有一个内部包含数组的类型。 我需要一个函数,该函数返回A或1(如果类型不是A)中的数组成员数。

这是代码:

#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'
                                    ^

功能不能部分专门化。 相反,您可以使用可以部分专门化的类:

#include <cstdio>
template<typename T, unsigned n>
struct A
{
    T values[n];
};

template<typename T>
struct component_counter
{
    static unsigned count()
    {
        return 1;
    }
};
template<typename T, unsigned n>
struct component_counter<A<T, n> >
{
    static unsigned count()
    {
        return n;
    }
};
int main()
{
    printf("%d\n", component_counter<A<float, 4> >::count());//should be 4
    printf("%d\n", component_counter<float>::count());//should be 1
    return 0;
}

在这种情况下,count()实际上根本不必是一个函数! 您可以这样做:

#include <cstdio>
template<typename T, unsigned n>
struct A
{
    T values[n];
};

template<typename T>
struct component_counter
{
    static const unsigned count=1;
};
template<typename T, unsigned n>
struct component_counter<A<T, n> >
{
    static const unsigned count=n;
};
int main()
{
    printf("%d\n", component_counter<A<float, 4> >::count);//should be 4
    printf("%d\n", component_counter<float>::count);//should be 1
    return 0;
}

更少的代码。 需要注意的是,计数必须是不可或缺的类型才能起作用。

当我有函数时,我更喜欢保留函数(这对成员函数更有利,因为您仍然可以访问*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>());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM