Search code examples
c++templatesnon-type

Right syntax for a C++ non-type template template with a given type


I have a class templated over a non-type attribute pointer over a template type, here a std::optional.

#include <optional>

class A
{
public:
  std::optional<int> i;
};

template <typename C, typename T, std::optional<T> C::*optionalPtr>
class OptionalHolder3
{
    void doStuff(C &c);
};

using OH3 = OptionalHolder3<A, int, &A::i>;

It works well but I was curious if I could make it easier to use, by reducing the number of required template arguments, but I can't find the right syntax:

// Doesn't compile
template <typename C, template<class T> std::optional<T> C::*optionalPtr>
class OptionalHolder2
{};

// Doesn't compile
template <template<class C, class T> std::optional<T> C::*optionalPtr>
class OptionalHolder1
{};

using OH2 = OptionalHolder2<A, &A::i>;
using OH2 = OptionalHolder1<&A::i>;

Is this possible and how do I do it?


Solution

  • You might use auto (C++17) for that:

    template <auto>
    class OptionalHolder; // No definition
    
    template<typename C, typename T, std::optional<T> C::*optionalPtr>
    class OptionalHolder<optionalPtr>
    {
        void doStuff(C &c);
    };
    

    concepts from C++20 might be used instead of that specialization, but it would require some traits to extract T and C.