1

Here is the trivial example of code I want to write:

#include <stdexcept>
#include <iostream>

template<typename T>
T test() {
    static_assert(false, "test not implemented for type T");
    // throw std::runtime_error("test not implemented for type T");
}

template<>
int test<int>() {
    return 5;
}

int main() {
    std::cout << test<int>() << std::endl;
    return 0;
}

Even though the template function of type T is never required by the program (only the specialised template is), the compiler does not like this:

main.cpp: In function ‘T test()’:
main.cpp:14:19: error: static assertion failed: test not implemented for type T
   14 |     static_assert(false, "test not implemented for type T");

Is there a good reason something like this isn't possible?

I would love to have compile time rather than runtime implementation checks. If I switch to the runtime error, the code works as intended.

Will T
  • 43
  • 5
  • 2
    Static assert do not depend on template parameter so it is triggered immediately before any template is instantiated. A good workaround: `static_assert(sizeof(T) == -1, ...`. https://godbolt.org/z/znTrjEc4e – Marek R May 31 '23 at 16:50
  • Current best practice is to use something like Microsoft's [`_Always_false`](https://github.com/microsoft/STL/blob/6a9845652ae9692d33fba07a4c431a082f7c2399/stl/inc/type_traits#L23-L25), but it's still [ill-formed, NDR](https://timsong-cpp.github.io/cppwp/n4868/temp.res#general-8.1). Best way would be if `static_assert(false)` would be only triggered at instantiation (i.e. it wouldn't make the program ill-formed), and also this [= delete("message")](https://groups.google.com/a/isocpp.org/g/std-proposals/c/KJnEmDp27Fo/m/ag3SwvSYCAAJ) idea is worth mentioning. – Dr. Gut May 31 '23 at 17:26
  • 1
    use the method in (both) duplicate or what @‌MarekR said and it's not ifndr. – apple apple May 31 '23 at 18:38

0 Answers0