mirror of
https://github.com/boostorg/utility.git
synced 2025-10-27 14:31:38 +01:00
Tests for enable_if
[SVN r1401]
This commit is contained in:
74
test/enable_if_lazy.cpp
Normal file
74
test/enable_if_lazy.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
//
|
||||
// Copyright 2003 <20> The Trustees of Indiana University. All rights
|
||||
// reserved.
|
||||
//
|
||||
// See the file enable_if_LICENSE for licensing conditions.
|
||||
//
|
||||
// Authors: Jaakko J<>rvi (jajarvi@osl.iu.edu)
|
||||
// Jeremiah Willcock (jewillco@osl.iu.edu)
|
||||
// Andrew Lumsdaine (lums@osl.iu.edu)
|
||||
//
|
||||
|
||||
#include <boost/test/minimal.hpp>
|
||||
|
||||
#include <boost/utility/enable_if.hpp>
|
||||
#include <boost/type_traits/is_arithmetic.hpp>
|
||||
|
||||
using boost::enable_if;
|
||||
using boost::enable_if_lazy;
|
||||
using boost::is_arithmetic;
|
||||
|
||||
// This class provides a reduced example of a traits class for computing
|
||||
// the result of multiplying two types. The exists constant is true when a
|
||||
// multiplication operator exists between two types, and the type member is
|
||||
// defined to the return type of this operator. The return type member is
|
||||
// not defined when a multiplication operator does not exist.
|
||||
|
||||
template <class T, class U>
|
||||
struct mult_traits {
|
||||
BOOST_STATIC_CONSTANT(bool, exists = false);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct mult_traits<int, int> {
|
||||
BOOST_STATIC_CONSTANT(bool, exists = true);
|
||||
typedef int type;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct mult_traits<double, double> {
|
||||
BOOST_STATIC_CONSTANT(bool, exists = true);
|
||||
typedef double type;
|
||||
};
|
||||
|
||||
// Next, a forwarding function mult() is defined. It is enabled only when
|
||||
// mult_traits<T, U>::exists is true. The first version, using normal
|
||||
// enable_if, works with only some compilers (it does not work in g++):
|
||||
|
||||
#if 0
|
||||
template <class T, class U>
|
||||
typename enable_if<
|
||||
mult_traits<T, U>::exists,
|
||||
typename mult_traits<T, U>::type>::type
|
||||
mult(const T& x, const U& y) {return x * y;}
|
||||
#endif
|
||||
|
||||
// An improved version that works with more compilers uses enable_if_lazy.
|
||||
// This template removes compiler errors from invalid code used as an
|
||||
// argument to enable_if.
|
||||
|
||||
template <class T, class U>
|
||||
typename enable_if_lazy<
|
||||
mult_traits<T, U>::exists,
|
||||
mult_traits<T, U> >::type
|
||||
mult(const T& x, const U& y) {return x * y;}
|
||||
|
||||
int test_main(int, char*[])
|
||||
{
|
||||
|
||||
BOOST_TEST(mult(1, 2) == 2);
|
||||
BOOST_TEST(mult(1.0, 3.0) == 3.0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user