Traits and Policies

Trait和Policy都是模板的应用,从这两个东西里面,第一眼看到的是"编译时多态",再一次感叹模板的强大,再一次清楚地认识到我只是个初学者,而且在未来很长一段时间都将是初学者.

一个Policy的例子(使用模板的模板参数实现)

#include <iostream>

template<typename T>
struct addPolicy
{
  static T calculate(const T& lhs, const T& rhs)
  {
    return lhs + rhs;
  }
};

template<typename T>
struct mulPolicy
{
  static T calculate(const T& lhs, const T& rhs)
  {
    return lhs * rhs;
  }
};

template<typename T, template<typename> class Policy = addPolicy> // black magic
class Operate
{
  public:
    T calculate(const T& lhs, const T& rhs)
    {
      return Policy<T>::calculate(lhs, rhs);
    }
};

int main()
{
  Operate<int> op;
  std::cout << op.calculate(3, 4) << std::endl; // print 7
  Operate<int, mulPolicy> op1;
  std::cout << op1.calculate(3, 4) << std::endl; // print 12
}

一个Trait的例子

#include <iostream>
#include <string>

template<typename T>
struct Trait
{
	typedef T type;
	static void print()
	{
		std::cout << "not support\n";
	}
};

template<>
struct Trait<int>
{
	typedef int type;
	static void print()
	{
		std::cout << "bool\n";
	}
};

template<>
struct Trait<bool>
{
	typedef bool type;
	static void print()
	{
		std::cout << "int\n";
	}
};

template<typename T>
class Test
{
public:
	void display()
	{
		Trait<T>::print(); // compile time polymorphism 
	}
};

int main()
{
	Test<bool> t;
	t.display();  // print bool

	Test<int> t1;
	t1.display();  // print int

	Test<std::string> t2;
	t2.display();  // print not support
}

Traits和Policies的区别

Stock Overflow上有一个回答如下

Policies
Policies are classes (or class templates) to inject behavior into a parent class, typically through inheritance. Through decomposing a parent interface into orthogonal (independent) dimensions, policy classes form the building blocks of more complex interfaces.

Traits
Traits are class templates to extract properties from a generic type. There are two kind of traits: single-valued traits and multiple-valued traits.