Question

Whats wrong with this?

I thought this should work when using enable if???

Help??

Shouldnt the second constructor be excluded?

#include <iostream>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>



template<class T>
class integral_holder{
public:
integral_holder(T value_, typename boost::enable_if_c< boost::is_integral<T>::value>::type* ignore = 0) : value(value_){
    std::cout << "Integral" << std::endl;
}

integral_holder(T value_, typename boost::enable_if_c< boost::is_floating_point<T>::value>::type* ignore = 0) : value(floor(value_)){
    std::cout << "Floating point" << std::endl;
}

private:
  T value;

};

int main(int argc, const char * argv[])
{

   integral_holder<int> a(22);

   return 0;
}
Was it helpful?

Solution

When a class is generated out of the class template and in that process declarations of the constructors are instantiated (not theiry body, but just their "signature"), the enable_if type is invalid and you get a compiler error.

You need to make the enable_if type depend on a template parameter of the constructor (make it a function template). Your goal then works because the invalid type then is formed during deducing the function template parameter type when you use the constructor which will trigger an SFINAE case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top