Simple specialization problem

M

mathieu

Hello,

I am trying to express a very simple piece of code. I have:

#include <iostream>

enum A { a1, a2, a3, a4 };
enum B { b1, b2, b3, b4 };

template <int TA, int TB> struct Foo {
void foo() { std::cout << "general\n"; }
};

Now I want to say : only allow TB=b1 when TA=a1:

template<> struct Foo<a1,b1> {
void foo() { std::cout << "duplicated\n"; }
};
// mark everything else illegal:
template<int TB> struct Foo<a1, TB>;

This is working for me. The problem is that I need to duplicate the
code for Foo<a1,b1> when I simply want to use the general
implementation. Is there a way to say:

template <> struct Foo <a1,b1> : public Foo<a1,b1> ?

Or is there another way to achieve a compilation error for Foo <a1, `b!
=b1`>

Thanks
-Mathieu
 
A

Alan Johnson

mathieu said:
Hello,

I am trying to express a very simple piece of code. I have:

#include <iostream>

enum A { a1, a2, a3, a4 };
enum B { b1, b2, b3, b4 };

template <int TA, int TB> struct Foo {
void foo() { std::cout << "general\n"; }
};

Now I want to say : only allow TB=b1 when TA=a1:

template<> struct Foo<a1,b1> {
void foo() { std::cout << "duplicated\n"; }
};
// mark everything else illegal:
template<int TB> struct Foo<a1, TB>;

This is working for me. The problem is that I need to duplicate the
code for Foo<a1,b1> when I simply want to use the general
implementation. Is there a way to say:

template <> struct Foo <a1,b1> : public Foo<a1,b1> ?

Or is there another way to achieve a compilation error for Foo <a1, `b!
=b1`>

Thanks
-Mathieu

You could use boost's metaprogramming library. Something like:

#include <iostream>
#include <boost/static_assert.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/not_equal_to.hpp>
#include <boost/mpl/comparison.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/logical.hpp>
#include <boost/mpl/assert.hpp>

enum A { a1, a2, a3, a4 };
enum B { b1, b2, b3, b4 };

using namespace boost::mpl ;

template <int TA, int TB> struct Foo {

BOOST_MPL_ASSERT(( or_< not_equal_to< int_<TA>, int_<a1> > ,
equal_to< int_<TB>, int_<b1> > > )) ;
void foo() { std::cout << "general\n"; }
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top