Search code examples
c++templatesc++17type-level-computation

Type Level Function in C++


I currently have a class

template <typename T, typename Context>
class Foo {
    T value;
    Context context;
}

What is frustrating is that the value of T completely determines the value of Context, so the second term is rather redundant. In similar situations, I have added a Context type to the class and then written the function as

template <typename T>
class Foo {
    T value; 
    T::Context context;
}

Unfortunately, I cannot do the same here, as 90% of the calls to foo are on int and double and I cannot modify the type.

Is it possible to write a type level function that takes my initial type and returns the related type. I'm imagining something along the lines of.

template <typename T> typename FooContext;
using FooContext<int> = std::string;
using FooContext<NodeValue> = NodeValue::Context;

template <typename T>
class Foo {
    T value; 
    FooContext<T> context;
}

As an added challenge, our project is on C++17, so answers that do not require C++20 Concepts will be given priority.


Solution

  • Not directly with alias, but with regular class, it is possible:

    template <typename T> struct FooContext
    {
        using type = typename T::Context;
    };
    template <> struct FooContext<int>
    {
        using type = std::string;
    };
    
    // Other specialization as `double`.
    
    template <typename T>
    using FooContext_t = typename FooContext<T>::type;
    
    template <typename T>
    class Foo {
        T value; 
        FooContext_t<T> context;
    };