Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ templates policy with arguments

I am new to this. I am creating a class with policies say:

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

{
    ...
}

The problem I have is that some of the policies have arguments, and when they are compile time it is ok

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

but when they are runtime I am not sure what is the best way to provide the policy class object ... or this is no longer a policy pattern?

like image 701
gsf Avatar asked Jan 06 '14 21:01

gsf


1 Answers

You can have a factory for the policy :) 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 explicit constructors obviously spell it out:

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

See it Live on Coliru


Update: Factories

Here's an update showing the factory approach:

#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;
}

See it Live on Coliru*

Note that

  • I prefer the constructor pass-in approach
  • The factory is technically a trait class
like image 64
sehe Avatar answered Oct 02 '22 03:10

sehe