std::enable_if
如果其中一个子类定义了特定的成员函数,我正在尝试使用它来专门化一个类。否则,它应该使用在基类中定义的默认实现。
#include <boost/mpl/list.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/tti/has_member_function.hpp>
#include <iostream>
#include <type_traits>
#include <memory>
BOOST_TTI_HAS_MEMBER_FUNCTION(f2)
class Base
{
public:
virtual double f1(double x, double y) const
{
std::cout << "Called Base Method" << std::endl;
return 0.0;
}
};
template<typename Derived>
class A : public Base
{
public:
template<typename T = Derived>
typename std::enable_if
< has_member_function_f2< T
, double
, boost::mpl::list<double>
, boost::function_types::const_qualified
>::value
, double
>::type
f1(double x, double y) const
{
std::cout << "Called Derived Method" << std::endl;
return static_cast<const Derived* const>(this)->f2(x);
}
};
class B : public A<B>
{
public:
double f2(double x) const
{
return 1.0;
}
};
int main()
{
std::unique_ptr<Base> base_instance( new B );
std::cout << base_instance->f1(100.0, 10.0) << std::endl;
B b_instance;
std::cout << b_instance.f1(100.0, 10.0) << std::endl;
return 0;
}
我本来希望这会打印
Called Derived Method
1
Called Derived Method
1
但是相反,我得到
Called Base Method
0
Called Derived Method
1
所以看起来正在发生一些对象切片。我一生都无法理解为什么会这样,如果有人可以帮助我,将不胜感激。
如果它有任何帮助,那么它正在使用 g++ 4.7.2 进行编译