David Abrahams wrote:
Angus Leeming
writes: Is it possible to use enable_if with a constructor?
In principle, yes. You just add a dummy default parameter for the enabler.
For example, I'd like to define a constructor that allows only certain values of an enum:
No chance; that's a runtime test... or you'd have to specify the enum as a template argument to the ctor explicitly... but you can't provide explicit template arguments to ctors.
Many, many thanks, Dave, both for the explanations and for the working
code.
Your code worked perfectly of course, but I decided to use a static "set"
member function to return a foo instance:
foo x(foo::setfoo::state2());
I guess that this is semantically equivalent to your
foo x(mpl::int_foo::state2());
FWIW, I include my working version of this MPL code at the bottom of this
mail. However, it all seems like a lot of machinery. In my case, there are
only a few "valid" enum values. What are the advantages of the Boost.MPL
approach over the functionally identical:
#include <iostream>
class foo {
public:
enum state {
state1,
state2,
state3
};
// Only the specializations (below) of this template will compile.
template <int N>
static foo
set() { return invalid_value; }
private:
foo(state)
{
std::cout << "foo" << std::endl;
}
};
template <>
foo foo::setfoo::state2() { return foo::state2; }
template <>
foo foo::setfoo::state3() { return foo::state3; }
int main()
{
// Compiles, as expected.
foo f1 = foo::setfoo::state2();
foo f2(foo::setfoo::state2());
// Fail to compile, as expected.
// foo f3 = foo::setfoo::state1();
// foo f4(foo::setfoo::state1());
return 0;
}
Regards,
Angus
-----------------------------------------------------------------------
My version of Dave Abrahams's working version of my broken original ;-)
#include
>
>::type
, typename end<S>::type
>
>
{};
} // namespace boost
} // namespace mpl
class foo {
public:
enum state {
state1,
state2,
state3
};
// Will compile only for state2 and state3
template <int N>
static
typename boost::enable_if<
typename boost::mpl::contains_c<
boost::mpl::vector_c