It is possible to restrict template parameter?
template <class T>
class myclass
{
...
};
For example I want that T might be int double or my own defined complex but nothing else!
Sadly, constraints are not a part of C++, and concepts (the design for constraints) have been dropped from the next revision of the standard. However, you can fake it using static assertions and template specialization:
#include <iostream>
#define STATIC_ASSERT(condition) \
do \
char foo[condition] = {0}; \
while ( false );
template <class T>
class myclass
{
public:
myclass() { enforce_constraint(); }
private:
void enforce_constraint()
{
STATIC_ASSERT ( false );
}
};
template<>
void myclass<int>::enforce_constraint() {}
int main()
{
myclass<double> a;
myclass<int> b;
}
The error is uninformative, but that's because the static assertion is very simple and naive. There are better ways, such as Boost's static assert.
Posted in the correct thread this time. This is also another way, and still
naive. It shows both static_assertion and exceptions.
#include<iostream>
using namespace std;
template<typename Type>
struct assert_numeric{ const static int i = 0; };
template<> struct assert_numeric<short> { const static int i = 1; };
template<> struct assert_numeric<unsigned short> { const static int i = 1; };
template<> struct assert_numeric<int> { const static int i = 1; };
template<> struct assert_numeric<unsigned int> {const static int i = 1; };
template<> struct assert_numeric<float> { const static int i = 1; };
template<> struct assert_numeric<double> { const static int i = 1; };
template<typename Type>
class Numeric{
public:
struct BadType : std::exception{
BadType(const char *msg) : exception(msg){}
};
public:
Numeric()
{
//int asserter[assert_numeric<Type>::i];// Way# 1 cannot have an array of size 0
if(assert_numeric<Type>::i == 0) //Way number 2 : throw custom exception
throw BadType("Type is not numerical!");
}
~Numeric(){ }
};
int main()
{
try{
Numeric<char> j;
}
catch(Numeric<char>::BadType& e){ cout << e.what() <<endl; }
return 0;
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.