1

私は比較的一般的なものを探しています:

  1. このコード行をコンパイルしてみてください
  2. それが成功した場合は、そのコード行をコンパイルして使用します。さもないと
  3. 他のコード行を使用する

double提供されたファンクターがsで有効かどうかに基づいて、何かを選択的にコンパイルしたい場合があります。

//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.");
}

最初のオーバーロード (double を渡した場合により良いオーバーロードであるため選択される) で置換が失敗し、その制御が 2 番目のオーバーロードに進むと考えました。ただし、とにかく全体がコンパイルに失敗します。

私がやろうとしていることは合理的または可能ですか?

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 に答える