简体   繁体   English

模板特化功能参数计数

[英]template specialization function parameter count

Ok, an update to my previous question about templates ( I'm such a noob on this field )... I resumed most of my questions to: Is it possible to have a different parameter count for a member function, depending on the template parameter used on the class declaration? 好的,是我之前关于模板的问题的更新(我在这个领域是个菜鸟)...我将大部分问题恢复为:取决于模板,成员函数是否可以具有不同的参数计数类声明中使用的参数?

For example, a constructor: 例如,一个构造函数:

template <typename Type, unsigned ElementCount>
class TVector
    {
    public:
    Type Values[ElementCount];

    TVector ( ElementCount number of Type here )
        { ...

Is this possible? 这可能吗? Or perhaps a setter: 也许是二传手:

SetValues ( ElementCount number of Type here );

EDIT: Ok, my mistake, i did not explain fully. 编辑:好的,我的错误,我没有完全解释。 This vector is a trigonometry vector, not an array of elements. 此向量是三角向量,而不是元素数组。 So, it should support 2, 3 or 4 values. 因此,它应该支持2、3或4个值。

As for the constructor, i wanted to be able to do something like: TVector xpto ( 0.0f, 0.0f, 0.0f, 1.0f ); 对于构造函数,我希望能够执行以下操作:TVector xpto(0.0f,0.0f,0.0f,1.0f);

As for compiler, i'm using gcc, and dunno if it's safe to enable more recent c++ standards. 至于编译器,如果可以安全地启用最新的c ++标准,我将使用gcc和dunno。 It does complain about it, when i enable them. 当我启用它们时,它确实对此有所抱怨。 So, no enable_if for me :) 因此,对我来说没有enable_if了:)

Thanks. 谢谢。

The member function can have as parameter a std::initializer_list<T> type that will let it access any number of objects of type const T. In that case, ElemCount, in the class template, can be removed as you don't have to specify number of arguments. 成员函数可以具有std::initializer_list<T>类型作为参数,该类型将使其可以访问任意数量为const T的对象。在这种情况下,可以删除类模板中的ElemCount,因为您没有指定参数数量。

template <typename Type>
class TVector
    {
    public:    

    TVector ( std::initializer_list<Type> l )
        { ...

Yes, you can, using std::enable_if . 是的,您可以使用std::enable_if

template <typename T, typename ... Ts>
struct AllSameAsT : public std::false_type
{
};

template <typename T>
struct AllSameAsT<T> : public std::true_type
{
};

template <typename T, typename T, typename ... Ts>
struct AllSameAsT : public AllSameAsT<T, Ts...>
{
};


template <typename Type, unsigned ElementCount>
class TVector
    {
    public:
    template <typename ... Ts, typename = std::enable_if_t<AllSameAsT<Type, Ts...>::value && (sizeof...(Ts) == ElementCount)>
    TVector (Ts... ts);
    };

If you don't have C++14, you would also need to add 如果您没有C ++ 14,则还需要添加

template< bool B, class T = void >
using enable_if_t = typename enable_if<B,T>::type;

As JosephMansfield has pointed out in the comments, a simpler solution might be to just accept an std::array<Type, ElementCount> . 正如JosephMansfield在评论中指出的那样,一个更简单的解决方案可能是只接受std::array<Type, ElementCount>

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

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