5

Is there an elegant way to perform a conditional static_assert in c++11

For example:

template <class T> class MyClass { COMPILE_TIME_IF( IsTypeBuiltin<T>::value) static_assert(std::is_floating_point<T>::value, "must be floating pt"); }; 
8
  • 2
    Have you considered using the && operator or is this not a viable alternative? Commented Sep 8, 2015 at 6:42
  • && would work, maybe I should've rephrase the question as a 'compile time if' based on type Commented Sep 8, 2015 at 6:43
  • 1
    @bendervader std::is_integral<T> and std::is_floating_point<T> are exclusive. What is it that you want to achieve? Commented Sep 8, 2015 at 6:48
  • I want to enable the static assert if and only if the type is integral. If the user passes their own class, I do not want to assert Commented Sep 8, 2015 at 6:49
  • @bendervader But, if T is integral, it can't be floating point. Commented Sep 8, 2015 at 6:50

1 Answer 1

10

Simple boolean logic within static_assert() should do it:

static_assert( (!std::is_fundamental<T>::value) || std::is_floating_point<T>::value, "must be floating pt" ); 

I.e. T is either not fundamental or it's floating point. In other words: If T is fundamental it must also be floating point.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.