Is there a better way to do the following?
#include <iostream>
template <typename T>
T Bar();
template <>
int Bar<int>() { return 3; }
// Potentially other specialisations
int main()
{
std::cout << Bar<int>() << std::endl; // This should work
std::cout << Bar<float>() << std::endl; // This should fail
}
The problem with this solution is that it fails at (understandably) link time with "undefined reference to float Bar<float>()
" or the like. This can be confusing for other developers as they may suspect an implementation file is not being linked.
I do know another potential solution:
template <typename T>
T Bar() { BOOST_STATIC_ASSERT(sizeof(T) == 0); }
This causes a compiler error when Bar<float>()
is requested, exactly what I want. However, I'm concerned that technically a compiler may reject this just as gcc rejects BOOST_STATIC_ASSERT(false)
because it knows that it will fail regardless of the template parameter, since sizeof(T)
can never be zero.
In summary, I want to know whether:
- There is another way to do this.
- I'm mistaken and
BOOST_STATIC_ASSERT(sizeof(T))
actually can't fail without instantiation. - The only way is to let this be a linker error as above.