Re: Constraints => Traits
Michael Aaron Safyan wrote:
I presently have types CopyableCONSTRAINT<T> and CloneableCONSTRAINT<T>
defined to require these respective functions and to generate
informative compiler errors in their absence.
I would like very much to define CopyableTrait<T> and CloneableTrait<T>
using these constraints. My current definition for CopyableTrait<T>
looks as follows (and CloneableTrait follows the same pattern):
template<typename T>
class CopyableTrait
: public Trait<false>{};
template<typename T>
class CopyableTrait< typename CopyableCONSTRAINT<T>::copyabletype >
: public Trait<true>{};
Unfortunately, the definition above does not seem to work
With some template metaprogramming, it is possible to determine whether
a class has a clone() or copy() method with the desired signature.
(Though I am curious what is the difference between a clone and a
copy?).
Here's one technique that I found it on the web:
#include <iostream>
#include <ios>
template<class T, T (T::*)() const>
struct mf_bind
{
typedef T type;
};
template<class T1, class T2>
struct has_copy_member
{
static const bool value = false;
};
template<class T>
struct has_copy_member<T,
typename mf_bind<T, &T::copy>::type>
{
static const bool value = true;
};
// A and B test classes
class A
{
public:
A copy() const;
};
class B {};
using std::cout;
int main()
{
cout << std::boolalpha;
cout << "A has copy member? ";
cout << has_copy_member<A, A>::value << "\n";
cout << "B has copy member? ";
cout << has_copy_member<B, B>::value << "\n";
}
Program Output:
A has copy member? true
B has copy member? false
To use these templates for your purposes, just declare CopyableTrait as
shown below (no specialization is needed):
template<typename T>
class CopyableTrait
: public Trait< has_copy_member<T, T>::value>
{};
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]