C ++ Output template arguments based on other template arguments

Suppose I have the following class:

template <class T, class U, class V> Foo
{
    ...
};

The template parameters are clearly mapped, so I can infer other template arguments U and V based on what T. is. For example, if T is double, U and V will always be some classes D1 and D2, and if T is float, U and V there will always be some other classes F1 and F2.

With that in mind, is there a way I can only pass one template argument and force the compiler to output two other parameters?

I know that the simple answer would be to simply make these other classes templates and pass the template argument T to them, but I cannot make these classes templates (they are automatically generated by the tool).

Ideally, I could use typedef or #define like this:

typedef Foo<double> Foo<double, D1, D2>
typedef Foo<float> Foo<float, F1, F2>

. , , , , , , . - ?

+5
2

, Angew, , , , U V .

, U V:

struct D1 { }; struct D2 { };
struct F1 { }; struct F2 { };

// Primary template
template<typename T>
struct deduce_from
{
};

// Specialization for double: U -> D1, V -> D2
template<>
struct deduce_from<double>
{
    typedef D1 U;
    typedef D2 V;
};

// Specialization for float: U -> F1, V -> F2
template<>
struct deduce_from<float>
{
    typedef F1 U;
    typedef F2 V;
};

// Give defaults to U and V: if deduce_from is not specialized for
// the supplied T, and U or V are not explicitly provided, a compilation
// error will occur 
template<
    typename T,
    typename U = typename deduce_from<T>::U,
    typename V = typename deduce_from<T>::V
    >
struct Foo
{
    typedef U typeU;
    typedef V typeV;
};

:

#include <type_traits>

int main()
{
    static_assert(std::is_same<Foo<double>::typeU, D1>::value, "Error!");
    static_assert(std::is_same<Foo<double>::typeV, D2>::value, "Error!");
    static_assert(std::is_same<Foo<float>::typeU, F1>::value, "Error!");
    static_assert(std::is_same<Foo<float>::typeV, F2>::value, "Error!");

    // Uncommenting this will give you an ERROR! 
    // No deduced types for U and V when T is int
    /* static_assert(
        std::is_same<Foo<int>::typeU, void>::value, "Error!"
        ); */
    static_assert(
        std::is_same<Foo<int, bool, char>::typeU, bool>::value, "Error!"
        ); // OK
    static_assert(
        std::is_same<Foo<int, bool, char>::typeV, char>::value, "Error!"
        ); // OK
}
+5

U V, :

template <typename T>
struct Foo
{
  typedef typename deduce_from<T>::U U;
  typedef typename deduce_from<T>::V V;
};

deduce_from .

+6

All Articles