Maik Klein
Maik Klein

Reputation: 16148

Template constraints in C++11

template<typename T>
T add(T a, T b){
    static_assert(std::is_integral<T>::value 
                 || std::is_floating_point<T>::value
                 , "Not a numeric value");
    return a + b;
}

Are there other/better ways to enforce constraints on templates?

Upvotes: 0

Views: 1249

Answers (2)

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

Why you're doing this? You can do it in Duck-Typing style: you don't check if the types fits, if there is no operator+ defined it simply doesn't compile.

#define RETURNS(WHAT) ->decltype(WHAT) {return WHAT;}
template<typename T>
auto add(T a, T b) RETURNS(a+b)

Upvotes: 1

CashCow
CashCow

Reputation: 31435

static_assert as you used will give the compiler error you specified if someone tries to invoke the template with an inappropriate type.

enable_if is an alternative, but will give an error that the template is not defined. This may well confuse a user who thinks it is defined, and would have to look at more detail.

Assuming you want

  1. The compilation to fail if an incorrect type is used (unless the user has written a specialization for their own type)

  2. The error given will be meaningful.

What you outlined above with static_assert seems a good way of achieving this.

Of course you have given us a very simple template and I am sure you are likely to be considering a more complex one.

Upvotes: 4

Related Questions