Search⌘ K

- Solution

Explore how to restrict a struct's constructor in C++ to accept only integers by using templates and the delete keyword. This lesson helps you understand enforcing type constraints at compile time, improving program safety and preventing unintended usage of your classes.

We'll cover the following...

Solution #

C++ 17
struct OnlyInt{
OnlyInt(int){}
template<typename T>
OnlyInt(T) = delete;
};
int main(){
OnlyInt(5);
OnlyInt(5L);
OnlyInt(5LL);
OnlyInt(5UL);
OnlyInt(5.5);
OnlyInt('5');
OnlyInt(true);
}

Explanation

...