1

I have some template functions & classes that when instantiated should fail compilation with given error message. I have used the following macro for it before and it has worked fine in Visual Studio & gcc:

#define PFC_CTF_ERROR(msg__) {struct cterror {char msg__:0;};}

Then if I have a template function I like to fail compilation upon instantiation I use it like this:

template<typename T>
void foo()
{
  PFC_CTF_ERROR(you_should_never_compile_this_function);
}

However, now I'm porting my code to clang/llvm and it's failing compilation even when the function isn't instantiated. So I tried static_assert(false, "message"); instead, but that fails as well (now even in MSVC). An option I thought was to use an expression dependent on template argument like this:

#define PFC_CTF_ASSERT_MSG(e__, msg__)  {struct cterror {char msg__:(e__);};}

template<typename T>
void foo()
{
  PFC_CTF_ASSERT_MSG(sizeof(T)==0, you_should_never_compile_this_function);
}

And it works fine but is quite cumbersome to use. Does anyone have an idea how this could be done better and maintaining the old PFC_CTF_ERROR() syntax?

JarkkoL
  • 1,898
  • 11
  • 17
  • ^ maybe some useful ideas there? – M.M Jul 08 '14 at 03:47
  • @MattMcNabb Thanks for the reference. All those answers pretty much say that you have to do the `sizeof(T)==0` trick. I wonder if there's any better solution. – JarkkoL Jul 08 '14 at 03:58

1 Answers1

2

You need to have a part of the condition depending on the template parameter. Otherwise, the compiler isn't required to put off evaluating it until template instantiation. That is the reason why sizeof(T)==0 works.

Pradhan
  • 16,391
  • 3
  • 44
  • 59