0

What should I do in the following function if the argument type T is wrong?

    template <class T>
    constexpr inline size_t GetObjectSize(const T & val)
    {
        if constexpr (std::is_arithmetic<T>::value)
        {
            return sizeof(val);
        }

        if constexpr (std::is_class<T>)
        {
            return 5u;
        }

        //there should be compile time error.
    }

    int * p;
    //compile time error
    GetObjectSize(p);

Possible alternatives are 1) throwing an exception 2) assert 3) static_assert

1) Exception of what type should I throw?

2) it is implementation defined and is not guaranteed to be a costexpr.

3) static_assert(false) always fails independently of T.

4
  • 1
    In this case perhaps specialization is better? And as always, doing switch or if checks on type is usually an anti-pattern. Commented Feb 25, 2019 at 12:49
  • @Someprogrammerdude yes, specialization looks better, because I need specialization for static_assert, see the answer. Commented Feb 25, 2019 at 13:15
  • @Someprogrammerdude it was not quite correct. static_assert(false) can be used with 'if else if else'. Commented Feb 25, 2019 at 13:21
  • @Someprogrammerdude static_assert(false) works with MSVC2017, but with GCC it does not. Commented Feb 25, 2019 at 14:48

1 Answer 1

3

static_assert(false) always fails independently of T.

Then make it dependent on T.

template<typename>
struct always_false { enum {value = 0}; };

// ...

if constexpr(...) {
}
else {
    static_assert(always_false<T>::value, "Some useful description");
}

Yes, it's a a magician's trick. But the dry letter of the law is okay with it. Sadly there isn't really a better way to print a useful diagnostic in a dependent branch of an if constexpr.

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

6 Comments

Are you sure static_assert should be in 'else' branch?
@AlexeyStarinsky - Of course. Otherwise it will be a part of all branches.
Moreover, your branches should really be an if else if else chain for this to work.
Yes, static_assert(false) works if there is 'if else if else'. So the answer is static_assert(false).
@AlexeyStarinsky - Which is why I did not suggest static_assert(false), but to make the condition formally dependent too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.