Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variadic template specialization (and static_assert)

Is it possible to specialize this template declaration:

template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) { 
    static_assert(false);
}

I tried a few things such as:

template <> int Foo<int>(float args) {
    return 42;
}

...but I always hit the static assert when I try to use it as such:

auto value = Foo<int>(1.5f);

What's the correct syntax?

like image 706
Deathicon Avatar asked Mar 11 '23 17:03

Deathicon


1 Answers

You're not allowed to write a template that is only valid as long as it isn't instantiated. That runs afoul of the following rule in the standard:

If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.

On the other hand, it would be fine if you had something in the body such as

static_assert(sizeof(TYPE) != sizeof(int));

In such a case, the template is valid, and your code will compile since the explicit specialization will in fact be used instead of the primary template. See http://coliru.stacked-crooked.com/a/238b979fd10c62c0

like image 113
Brian Bi Avatar answered Mar 17 '23 13:03

Brian Bi