C ++ template policy with arguments

I am new to this. I create a class with a policy:

template <typename T,
          typename P1 = Policy1<T>,
          typename P2 = Policy2<T> >

{
    ...
}

The problem is that some policies contain arguments, and when they compile, that's fine.

template <typename T,
          typename P1 = Policy1<T, size_t N>,
          typename P2 = Policy2<T> >

but when they are executed, I'm not sure what the best way to provide a policy class object is ... or is it not a policy template anymore?

+4
source share
2 answers

You may have a factory for politics :) EDIT See added below.

Ooor you can do as the standard library does:

#include <string>

struct DummyPolicy { };

template <typename>
struct Policy1 { Policy1(int, std::string) { } };

template <typename T,
          typename P1 = Policy1<T> >
struct X 
{
     X(P1 p1 = {}) : _policy1(std::move(p1)) { }

   private:
     P1 _policy1;
};

And use it

int main()
{
     X<int, DummyPolicy> no_questions_asked;
     X<int> use_params({42, "hello world"});
}

With C ++ 03 or an explicit constructor, it is obviously written:

     X<int> use_params(Policy1<int>(42, "hello world"));

Watch Live on Coliru


Update: Factories

, factory:

#include <string>

namespace details
{
    template <typename PolicyImpl>
        struct PolicyFactory
        {
            static PolicyImpl Create() {
                return {};
            }
        };
}

template <typename>
struct Policy2 { Policy2(double) { } };

template <typename T,
          typename P1 = Policy2<T> >
struct X 
{
    X()      : _policy1(details::PolicyFactory<P1>::Create()) {}
    X(P1 p1) : _policy1(std::move(p1)) { }

  private:
    P1 _policy1;
};

///// supply a factor, possibly local to a TU:

namespace details
{
    template <typename T>
        struct PolicyFactory<Policy2<T> > {
            static Policy2<T> Create() { 
                return Policy2<T>(3.14);
            }
        };
}

int main()
{
     // with a factory:
     X<std::string, Policy2<std::string> > no_params_because_of_factory;
}

*

,

  • factory
+9

, ( , ++).

" ", , , , .

+4

All Articles