简体   繁体   中英

How to restrict a template class to except only enum data type

I have written a class where i am using an enum data types. Now i want to generalize it to work with any type of enum data list. Is there any way to write a template class which will accept only enum data types;

My question is how to restrict a template class to accept only enum data types.

Pretty simple in c++11 you can do std::is_enum . here is the example from the site.

#include <iostream>
#include <type_traits>

class A {};

enum E {};

enum class Ec : int {};

int main() 
{
    std::cout << std::boolalpha;
    std::cout << std::is_enum<A>::value << '\n';
    std::cout << std::is_enum<E>::value << '\n';
    std::cout << std::is_enum<Ec>::value << '\n';
    std::cout << std::is_enum<int>::value << '\n';
}

Here is a class that uses the feature.

template <typename T>
struct A {
    static_assert(std::is_enum<T>::value,"not an enum");
};  

You could also use boost's is_enum in an identical fashion if you don't have c++11, remember boost is open source so you can check out the code if you don't want the whole thing.

Using <type_traits> :

#include <type_traits>

template <typename T>
struct foo
{
    static_assert(std::is_enum<T>::value, "Must be an enum type");
    ....
};

Without using C++11, you can do it by specifying the enum type as the template parameter type, if you want to limit it to a specific enumerated type:

#include <iostream>

enum fred { A, B };

template <fred F>
void f(void) { std::cout << F << std::endl; }

int main()
{
    f<B>();  // works
    f<1>(); // generates an error
}

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