Daniel Pitts wrote:
I have a template:
template<typename c, unsigned size>
struct Vector {
c components[size];
template<unsigned index>
c &get() { return components[index]; }
};
Vector<double, 3vect;
Is there a way to cause vect.get<3>() to fail at compile time. but
vect.get<2>() have compile successfully?
Another alternative is to use boost::enable_if and mpl helpers.
#include <iostream>
#include <boost/mpl/and.hpp>
#include <boost/mpl/int.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/greater.hpp>
#include <boost/mpl/less.hpp>
namespace mpl = boost::mpl;
template < typename C, unsigned SIZE >
struct Vector
{
C components[SIZE];
template < unsigned I >
typename boost::enable_if
<
mpl::and_
<
mpl::greater< mpl::int_<I>, mpl::int_<-1
, mpl::less< mpl::int_<I>, mpl::int_<SIZE
>
, C &
>::type get()
{
return components[i];
}
};
int main()
{
Vector<double, 3v = { 42.3, 66.6, 0.1 };
std::cout << v.get<1>() << std::endl;
//std::cout << v.get<3>() << std::endl;
std::cin.get();
}
Of course, you'll probably wish to clean that up a bit by writing your
own range checking metafunction.