5

If I have a method accepting a template parameter that should be convertible to, base_of, or same type as the type that is returned, how should I do?

For instance, consider this method:

template <class T>
class IFoo
{
public:
    template <class ServiceT>
    T* as()
    {
        static_assert(std::is_same< T, ServiceT >::value
                      || std::is_convertible< T, ServiceT >::value
                      || std::is_base_of< ServiceT, T >::value,
                      "IFoo< T >::as< ServiceT >() requires ServiceT to be a base of T");
        ...
    }
};

now, I would like to BOOST_CHECK it!

class A {};
class B {};

BOOST_AUTO_TEST_CASE(registering_incompatible_types_should_raise_a_static_assert_failure)
{
    BOOST_CHECK_STATIC_ASSERT_FAILURE(IFoo< A* >().as< B* >());
}

I want this BOOST_CHECK to compile fine and pass as well. But, I want user code to fail compiling when he actually does something like this :

void myAwesomeMethod()
{
    auto result = IFoo< A* >().as< B* >();

    ...
}

Any idea?

mister why
  • 1,967
  • 11
  • 33
  • 1
    Do you try to test a function that accepts only `Bar` argument by trying to pass a totally unrelated `Foo` argument. static_assert is a compile time construct and as such you don't need to test that constraint ? – parapura rajkumar Jan 15 '12 at 14:40
  • @parapura rajkumar, you're right. Unit testing this only proves it is type-safe -- I would like to catch static_assert failures and raise them to a higher level in my api. I would like to get a static_assert failure as close to the dev code as possible so the compile errors are more relevant. – mister why Jan 15 '12 at 14:53
  • 1
    @mister why Don't you just have to trust your users to know what they've coded at some point? – Mark B Jan 15 '12 at 16:14

1 Answers1

7

For your information, compile-time failure usually prevent the compilation... this is why they are here after all.

I can think of two ways to do what you are proposing:

  • using SFINAE
  • using compiler specific options

SFINAE

Literally, SFINAE means: Substitution Failure Is Not An Error. It applies to template context and allows functions that prove inadequate to be discarded quietly from the overload set. The use of SFINAE has given rise to the idea of Concept Checking and the categorization of properties using traits that is used to support those checks.

In your case, it means that if you can somehow put the expression you want to test in a context in which SFINAE may apply then you could try and detect that the particular function has been effectively discarded.

For example:

#include <iostream>
#include <utility>

struct Foo {};
struct Bar {};

template <typename T>
auto foo(T t) -> decltype(std::declval<Foo>() + t) { std::cout << "T\n"; }

void foo(...) { std::cout << "ellipsis\n"; }

int main() { foo(Bar()); }

yields:

ellipsis

(see ideone) even though there is no operator+(Foo, Bar) defined anywhere.

Unfortunately, this may not work in all cases (unsure yet), but it should be portable on all compliant compilers.

Compiler specific

Another possibility is to use compiler specific features. Compiler test suites must verify that those compilers correctly diagnose the errors, and in your case do emit an error when the static_assert condition is met. Therefore the compilers probably have hooks for this.

For example, in the Clang test suite one can find a SemaCXX/static-assert.cpp file:

// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x

int f();

static_assert(f(), "f"); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(true, "true is not false");
static_assert(false, "false is false"); // expected-error {{static_assert failed "false is false"}}

void g() {
    static_assert(false, "false is false"); // expected-error {{static_assert failed "false is false"}}
}

class C {
    static_assert(false, "false is false"); // expected-error {{static_assert failed "false is false"}}
};

template<int N> struct T {
    static_assert(N == 2, "N is not 2!"); // expected-error {{static_assert failed "N is not 2!"}}
};

T<1> t1; // expected-note {{in instantiation of template class 'T<1>' requested here}}
T<2> t2;

template<typename T> struct S {
    static_assert(sizeof(T) > sizeof(char), "Type not big enough!"); // expected-error {{static_assert failed "Type not big enough!"}}
};

S<char> s1; // expected-note {{in instantiation of template class 'S<char>' requested here}}
S<int> s2;

The -fsyntax-only avoid code generation and -verify means that the compiler checks that the expected-note, expected-warning and expected-error specified are correctly met.

If they are not, then the compiler will return with an error code. Of course, this is likely to be compiler specific.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722