Jump to content

  • Log In with Google      Sign In   
  • Create Account

Using static_assert to force use of template function specialisation.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
7 replies to this topic

#1 rbritt   Members   -  Reputation: 375

Like
0Likes
Like

Posted 16 April 2013 - 03:10 PM

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, 16 April 2013 - 03:10 PM.


Sponsor:

#2 Cornstalks   Crossbones+   -  Reputation: 6991

Like
2Likes
Like

Posted 16 April 2013 - 03:30 PM

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

Edited by Cornstalks, 16 April 2013 - 03:53 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#3 rbritt   Members   -  Reputation: 375

Like
0Likes
Like

Posted 16 April 2013 - 03:30 PM

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'");
	}


#4 rbritt   Members   -  Reputation: 375

Like
0Likes
Like

Posted 16 April 2013 - 03:33 PM

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.



#5 rbritt   Members   -  Reputation: 375

Like
0Likes
Like

Posted 16 April 2013 - 03:36 PM

Great! That did the trick! Thanks a lot :)



#6 Cornstalks   Crossbones+   -  Reputation: 6991

Like
0Likes
Like

Posted 16 April 2013 - 03:50 PM

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, 16 April 2013 - 03:51 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#7 BitMaster   Crossbones+   -  Reputation: 4432

Like
2Likes
Like

Posted 17 April 2013 - 01:03 AM

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.

#8 tivolo   Members   -  Reputation: 990

Like
0Likes
Like

Posted 17 April 2013 - 04:18 AM

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!






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS