Test for class operator?

I am writing a template class that relies on the existence of certain class operators in order to be valid. (Basically a heap template that relies on > and <).

What is the best way to do this? Is there a way to use the template keyword in such a way that the classes can be weeded out pre-compile time?

Another thought is to test for the existence of an operator within the class and throw an exception if it does not exist. I have heard that this is possible but do not know it is accomplished. How do you test to see if an operator is defined for a class?
Unfortunately, there is not. Just use the operators and if someone tries to use your template they will get a compile error message where you try to use the operators.

There is something called Concepts that would have allowed you to do that, but it was pushed back and not included in C++ currently. A modified version called Concepts Lite (IIRC) might be included in the newest standard that is under revision, but I don't remember for sure.
You can use SFINAE to check for method (and potentially freestanding functions) existence. Then use std::enable_if (form of SFINAE too) to allow/disallow template (not that it would make error messages make any more sense)

Some quick google search (untested):
http://stackoverflow.com/questions/87372/check-if-a-class-has-a-member-function-of-a-given-signature
http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
Or just use static_assert .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <utility>

template < typename T > struct heap
{
    static_assert( sizeof( std::declval<T>() < std::declval<T>() ) < 2, ""  ) ;
    static_assert( sizeof( std::declval<T>() > std::declval<T>() ) < 2, ""  ) ;
    // http://en.cppreference.com/w/cpp/utility/declval
    // http://en.cppreference.com/w/cpp/language/static_assert

    // ...
};


int main()
{
    heap<int> test_int ; // fine

    struct A{ bool operator< ( const A& ) { return false ; } };
    heap<A> test_A ; // *** error: no operator >
}

http://coliru.stacked-crooked.com/a/83638d3b3ffa4a69
Last edited on
Thanks JLBorges. That is exactly the kind of thing I was looking for
Topic archived. No new replies allowed.