1

我正在寻找一个相对通用的:

  1. 尝试编译这行代码
  2. 如果成功,编译并使用那行代码。否则
  3. 使用其他一些代码行

我有一个案例,我想根据提供的仿函数在doubles 上是否有效来选择性地编译一些东西:

//Some user supplied functor I can't modify which works on `int` but not `double`
template<typename T>
struct LShift : std::binary_function<T, T, T>
{
    T operator()(T lhs, T rhs)
    {
        return lhs << rhs;
    }
};

//Class that holds either an int or a double
class Example
{
    union
    {
        int intVal;
        double dblVal;
    } value;
    bool isIntType;
public:
    Example(int val)
        : isIntType(true)
    {
        value.intVal = val;
    }
    Example(double val)
        : isIntType(false)
    {
        value.dblVal = val;
    }
    int GetIntergalValue() const
    {
        return value.intVal;
    }
    double GetDoubleValue() const
    {
        return value.dblVal;
    }
    bool IsIntegral() const
    {
        return isIntType;
    }
};

//Does something with an example. I know that if the examples have `double` contents,
//that the functor passed will also be valid for double arguments.
template <template <typename Ty> class FunctorT>
Example DoSomething(const Example& lhs, const Example& rhs)
{
    if (lhs.IsIntergal() != rhs.IsIntergal())
    {
        throw std::logic_error("...");
    }
    if (lhs.IsIntegral())
    {
        return Example(FunctorT<int>(lhs.GetIntergalValue(), rhs.GetIntergalValue()));
    }
    else
    {
        return Example(FunctorT<double>(lhs.GetDoubleValue(), rhs.GetDoubleValue()));
    }
}


int main()
{
    DoSomething<LShift>();
}

我以前从未使用过 SFINAE,但这是我的第一次尝试:

template <template <typename Ty> class FunctorT>
double DoDouble(double lhs, double rhs)
{
    return FunctorT<double>()(lhs, rhs);
}

template <template <typename Ty> class FunctorT>
double DoDouble(int lhs, int rhs)
{
    throw std::logic_error("That is not valid on floating types.");
}

我认为在第一次重载时替换会失败(选择它是因为在传递双精度时它是一个更好的重载),然后该控制将继续进行第二次重载。但是,无论如何,整个事情都无法编译。

我正在尝试做的事情是合理的还是可能的?

4

1 回答 1

2

试试这个(它是即兴的,可能有语法错误):

template < class Type >
Type ShiftLeft( Type lhs, Type rhs )
{
    return LShift( lhs, rhs );
}

template <>
double ShiftLeft( double lhs, double rhs )
{
    assert( "ShiftLeft is not valid on floating types." && false );
    return 0;
}

或者,您可以通过 Boost 使用 SFINAE enable_if

但它有一种强烈的气味。没有调用特化(!)的代码很可能应该被重构。某种程度上来说。

干杯&hth.,

于 2011-06-23T21:39:47.480 回答