• Advertisement
Sign in to follow this  

Using static_assert to force use of template function specialisation.

This topic is 1740 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,
I've written some code which compiles as I want it to with MSVC 10 but I need the same code to compile with Clang too.
 
Basically I have a template helper function, but I want users to use the specialisations only. If they try to use the non specialised template function a static_assert triggers. It looks like this:

 

	template< typename T >
	T GetValue( const Variant& variant )
	{
		static_assert(0, "GetValue requires a template specialisation for 'T'");
	}

	template<> float GetValue(const Variant& variant)
	{
		return (float)variant.GetDouble();
	}
	
	template<> int GetValue(const Variant& variant)
	{
		return (int)variant.GetInt();
	}

	template<> bool GetValue(const Variant& variant)
	{
		return variant.GetBool();
	}

 

MSVC happily ignores the static_assert, but I'm finding that it's firing in Clang. Any clever ideas on how I can avoid that?

Edited by rbritt

Share this post


Link to post
Share on other sites
Advertisement
There's a better way (not to mention that's not quite right). First, you need to move the specializations outside of the class definition. Second, don't define the non-specialized template function (only declare it). Like this:
 
#include <iostream>
#include <type_traits> // for std::false_type

// You must use a helper class
template <typename T>
struct AlwaysFalse : std::false_type
{
};

struct S
{
  // Non-specializations can either be defined in or outside of class/struct
  template <typename T> T foo()
  {
    // You must make the static_assert depend on T,
    // otherwise it can be evaluated immediately by the
    // compiler (and should be, as clang does)
    static_assert(AlwaysFalse<T>::value, "noooo!");
    return T();
  }
};

// Explicit specializations need to be outside of the class/struct
template<>
int S::foo<int>()
{
  return 42;
}

template<>
float S::foo<float>()
{
  return 3.14f;
}

int main()
{
  S s;

  std::cout << s.foo<int>() << std::endl;
  std::cout << s.foo<float>() << std::endl;
  std::cout << s.foo<double>() << std::endl;
}

Here was my first suggestion, which does link-time checking (instead of compile-time checking, like the current code)
[spoiler]
#include <iostream>

struct S
{
  template <typename T> T foo(); // Just don't define the generic version!
};

template<> int S::foo<int>()
{
  return 42;
}

template<> float S::foo<float>()
{
  return 3.14f;
}

int main()
{
  S s;

  std::cout << s.foo<int>() << std::endl;
  std::cout << s.foo<float>() << std::endl;
  // s.foo<double>() will result in a linker error since it's never defined
}
[/spoiler] Edited by Cornstalks

Share this post


Link to post
Share on other sites

I managed to get something compiling but it's ugly... basically the static assert checks that the T isn't any of those taken by the specialisation functions. I don't like the maintenance overhead of this though :/

 

I'd be very interested to hear if anyone comes up with an improvement! Template functions are not my specialty, I'm sure there must be a nicer way.

 

	template< typename T >
	T GetValue( const Variant& variant )
	{
		static_assert( !(std::is_same<T,int>::value || 
						std::is_same<T, float>::value || 
						std::is_same<T, bool>::value )
			, "GetValue requires a template specialisation for 'T'");
	}

Share this post


Link to post
Share on other sites

I wrote my post the same time as yours, I'll give it a try - just don't implement the body eh? Sounds too easy! This is just a global template function btw.

Share this post


Link to post
Share on other sites

I wrote my post the same time as yours, I'll give it a try - just don't implement the body eh? Sounds too easy! This is just a global template function btw.

Heh, yeah, that's the simplest method. I edited my post though to use a version that does compile time checking (instead of link time checking), and kept screwing up and had to keep editing it. I finally got it though, and now it's pretty short and clean, and it gives a nice compile time error. Edited by Cornstalks

Share this post


Link to post
Share on other sites

MSVC happily ignores the static_assert, but I'm finding that it's firing in Clang. Any clever ideas on how I can avoid that?

While not providing the body at all is the obviously better solution, let's still dive into the mystery of why it works on MSVC and not on Clang/gcc.

Unfortunately MSVC is often extremely lazy with its templates and accepts nearly anything if the template is not instantiated yet (that's why early and thorough instantiation is an important sanity-preserving measure when using only MSVC to write and test templates).
Other compilers, like Clang and gcc, are doing what the standard asks of them on the other hand and do a lot of more checking before. And when they encounter a static_assert that does not use any of the template parameters they throw the glove down right away (and are within their rights to according to the standard).
So even with a body you would not need the monster you wrote later on, just

static_assert(sizeof(T) == 0, "...");
would have done the job.

Share this post


Link to post
Share on other sites

So even with a body you would not need the monster you wrote later on, just


static_assert(sizeof(T) == 0, "...");
would have done the job.

 

Wanted to suggest exactly the same, but got ninja'd. +1!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement