简体   繁体   中英

How to specialize a template for 2 different values?

Given the code below, I was wondering if it is possible to have a specialization for a set of values. In my example, I want to create an specialization for N=3 or N=4 to use an array of known size. Is it possible to avoid code duplication in this case?

template <typename T, unsigned int N>
class A
{
public:
    T* data;
};

template <typename T>
class A<T, 3>
{
public:
    T data[3];
};

template <typename T>
class A<T, 4>
{
public:
    T data[4];
};

int main()
{
    A<int, 1> u;
    std::cout << sizeof(u.data) << std::endl; // Size of pointer

    A<int, 3> v;
    std::cout << sizeof(v.data) << std::endl; // Size of data

    A<int, 4> w;
    std::cout << sizeof(w.data) << std::endl; // Size of data

    return 0;
}

You can use std::enable_if by introducing a default void template parameter in the general case.

template <typename T, unsigned int N, typename = void>
class A
{
public:
    T* data;
};

template <typename T, unsigned int N>
class A<T, N, typename std::enable_if<N == 3 || N == 4>::type>
{
public:
    T data[N];
};

live wandbox example


If N == 3 || N == 4 N == 3 || N == 4 is true , then typename std::enable_if<N == 3 || N == 4>::type typename std::enable_if<N == 3 || N == 4>::type is well-formed and evaluates to void . The specialization is then chosen.

If N == 3 || N == 4 N == 3 || N == 4 is false , then typename std::enable_if<N == 3 || N == 4>::type typename std::enable_if<N == 3 || N == 4>::type is ill-formed and the specialization is "SFINAEd away" . The general case is then chosen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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