std::enable_if, template specialization

Started by
14 comments, last by CodeCriminal 11 years, 7 months ago
Hello all, been a while since I've posted here.
I've run into a problem for which my google-fu is not strong enough. smile.png

I am attempting to tighten some of my own template library code using the std::enable_if and others
within the <type_traits> header, here is a hypothetical (cut-down) situation below.


// firstsomething.hpp
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, T>::type func(const T& x) noexcept
{ return /* something */ }

// something.hpp
template <> typename std::enable_if<true, mytype>::type func(const mytype& x) noexcept;

// something.cpp
template <> typename std::enable_if<true, mytype>::type func(const mytype& x) noexcept
{ return /* return other something */ }


Now, without the std::enable_if stuff and were I to replace this with just the bare types, the tests compiled and ran fine on GCC 4.7.1. However now I am having to wrestle with

error: template-id 'func<>' for 'std::enable_if<true, mytype>::type func(const mytype& x)' does not match any template declaration

So, where am I going wrong basically? smile.png

I did add 'template <typename T>' to the specializations instead of 'template <>' but doesn't this then mean the functions are no longer specializations of the original?

Thanks
Advertisement
With some support code it does compile in VC10 as the correct headers are included at the necessary places. Are you sure that the file containing the specialization actually includes the definition of the template so that the compiler sees a template to specialize in the first place?

I don't have GCC available to try at the moment so cannot verify if that is actually the error message you get under that circumstance.
Yeah just double checked and the header is being included. very odd because the error only crops up when I change the return type
of the template function to std::enable_if<...>::type
This code compiles in GCC 4.6. I don't have 4.7 to test with.

#include <type_traits>
// firstsomething.hpp
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, T>::type func(const T& x) noexcept
{ return x; }
// something.hpp
typedef int mytype;
template <> typename std::enable_if<true, mytype>::type func(const mytype& x) noexcept { return 0; }
int main() {
func(0.0);
func(0);
}


You could try changing the specialization to:

template <> typename std::enable_if<std::is_arithmetic<mytype>::value, mytype>::type func(const mytype& x) noexcept;


If that doesn't work, you might not need a function specialization in the first place (I'm not sure what exactly you're trying to do), so you ought to be able to use function overloading:

mytype func(const mytype& x) noexcept;



I did add 'template <typename T>' to the specializations instead of 'template <>' but doesn't this then mean the functions are no longer specializations of the original?
[/quote]
Yes. You can't have a partial function specialization in C++ so all function specializations must start with "template<>" (as far as I know).
EDIT: @sunder. I tried the little test example you gave which also compiled on gcc 4.7.1, however if you change mytype to a class instead of a simple typedef to one of the built in types, the problem I am having arises. here is what g++ had to say about it with code:

first.hpp

#ifndef __HEADER_FIRST_HPP__
#define __HEADER_FIRST_HPP__
#include <type_traits>
template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, int>::type func(const T& x)
{ return x; }
#endif //__HEADER_FIRST_HPP__


second.hpp

#ifndef __HEADER_SECOND_HPP__
#define __HEADER_SECOND_HPP__
#include "first.hpp"
class mytype { mytype( ) = default; };
template <> typename std::enable_if<true, int>::type func(const mytype& x)
{ return 0; }
#endif //__HEADER_SECOND_HPP__


main.cpp

#include <iostream>
#include "second.hpp"
int main(int, char**)
{
std::cout << func(1.0) << std::endl;
std::cout << func(mytype( )) << std::endl;
return 0;
}


In file included from main.cpp:2:0:
second.hpp:8:54: error: template-id 'func<mytype>' for 'std::enable_if<true, int>::type func(const mytype&)' does not match any template declaration
main.cpp: In function 'int main(int, char**)':
main.cpp:7:29: error: no matching function for call to 'func(mytype)'
main.cpp:7:29: note: candidate is:
In file included from second.hpp:4:0,
from main.cpp:2:
first.hpp:6:88: note: template<class T> typename std::enable_if<std::is_arithmetic<_Tp>::value, int>::type func(const T&)
first.hpp:6:88: note: template argument deduction/substitution failed:
first.hpp: In substitution of 'template<class T> typename std::enable_if<std::is_arithmetic<_Tp>::value, int>::type func(const T&) [with T = mytype]':
main.cpp:7:29: required from here
first.hpp:6:88: error: no type named 'type' in 'struct std::enable_if<false, int>'[/quote]


This code compiles in GCC 4.6. I don't have 4.7 to test with.

#include <type_traits>
// firstsomething.hpp
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, T>::type func(const T& x) noexcept
{ return x; }
// something.hpp
typedef int mytype;
template <> typename std::enable_if<true, mytype>::type func(const mytype& x) noexcept { return 0; }
int main() {
func(0.0);
func(0);
}



I actually had the implementation of the specialization in a seperate .cpp file, perhaps this is my error. I'll give it a go smile.png


You could try changing the specialization to:

template <> typename std::enable_if<std::is_arithmetic<mytype>::value, mytype>::type func(const mytype& x) noexcept;

[/quote]

I could try this but it would involve specializing is_arithmetic for mytype which is something I don't really want to do. Even still it would only evaluate to true and produce the same problems.


If that doesn't work, you might not need a function specialization in the first place (I'm not sure what exactly you're trying to do), so you ought to be able to use function overloading:

mytype func(const mytype& x) noexcept;

[/quote]

Yeah, it occurred to me that the specialization may not be necessary in the first place and I could have just created an overload (which is what I have done and it seems to work). I think I was concerned that creating an overload would break func for integer types because mytype does not have an explicit constructor and it still takes a single argument integer value. However this is not the case apparently.


I did add 'template <typename T>' to the specializations instead of 'template <>' but doesn't this then mean the functions are no longer specializations of the original?
[/quote]
Yes. You can't have a partial function specialization in C++ so all function specializations must start with "template<>" (as far as I know).
[/quote]

I'm pretty sure partial specializations are allowed for functions, what I had done was not a partial specialization.


I think I would be more comfortable with a template specialization in the header than an overload because of the potential problem I spoke about above. Lets see if it works smile.png

Yeah, it occurred to me that the specialization may not be necessary in the first place and I could have just created an overload (which is what I have done and it seems to work). I think I was concerned that creating an overload would break func for integer types because mytype does not have an explicit constructor and it still takes a single argument integer value. However this is not the case apparently.

If you have a template and an overloaded function that takes an object that in turn takes a single integer in a non-explicit constructor, then the template is a better match and will be chosen over the function that requires an implicit conversion (the constructor call). The implicit conversion is, as required by the language, the deciding factor not to choose the overloaded function over the template which requires no implicit conversion. You are safe on that point (assuming, of course, there is nothing preventing the template from being instantiated with the integer, in which case you may have problems).


I'm pretty sure partial specializations are allowed for functions, what I had done was not a partial specialization.

No, functions cannot be partially specialized, only fully specialized. Overloading serves (most of) the purpose of partial specialization for classes. The reason you can partially specialize classes is because you cannot overload them.


I think I would be more comfortable with a template specialization in the header than an overload because of the potential problem I spoke about above. Lets see if it works smile.png

If the potential problem is the int-conversion you mentioned earlier, then that is not a problem as I responded to above.
Ok, I guess the overload is my best bet for now seeing as the explicit specialization doesn't work, thanks Brother Bob, you learn something new everyday haha smile.png

EDIT: I have a question about not being able to partially specialize a function as this is news to me.
lets say that I have a template function that takes any type performs some operations and then returns, pretty basic stuff


template <typename T> void function(const T x) { /* ... */ }


Then I would like to "partially specialize" this function for pointers to T, I tried to create an overload like this:


template <typename T> void function(const T* x) { /* ... */ }


I have never had to do anything like this before but that is besides the point. While this compiles, I did not get the expected result
and only the first template function was being called, even when I passed a pointer to the function! Which to me is surprising.

Without being able to partially specialize a function, what would be the correct way to go about setting up something like this?

Thanks
That is not partial specialization, but regular function overloading. The two templates are separate.

I am not entirely sure about this explanation, but this is how I understand it and MSVC seems to support it as far as my testing goes at least. If you pass a pointer, then there has to be a mechanism to determine which one is called, of course, and the one with the best match is chosen. There are two things that are important:

  1. A const value in a parameter is redundant and, at least as far as function prototype matching goes, equivalent to the const not being there.
  2. A non-const overload is preferred over a const overload for a non-const parameter.

The meaning of point 1 is the following:

void foo(const int a);

int main()
{
int a = ...
foo(a);
}

void foo(int a)
{ ... }

The forward declaration of foo with a const has exactly the same prototype, as far as the parameter matching goes, as the definition of foo.

So, you have two overloaded templates: (a) one with a value parameter, and (b) one with a const-pointer parameter. If you pass a non-const int pointer, overload (a) with T=int * is in fact preferred over (b) because of point 2 above. If you have a const int pointer, then overload (b) with T=int is preferred over (a) because it's const, and the pointer-type overload is a better match than a value overload with T=int *.

So what you have is the correct way, but I suspect you're not failing to call the pointer-overload because the other overload a better match, but because you're passing a non-const pointer and non-const overloads are preferred over const-overloads in that case.

That is not partial specialization, but regular function overloading. The two templates are separate.


Haha I realized that, that is why I put "partial specialization" in inverted commas.


So what you have is the correct way, but I suspect you're not failing to call the pointer-overload because it's a better match, but because you're passing a non-const pointer and non-const overloads are preferred over const-overloads in that case.


Ah yes, I passed a const pointer to the function and the correct function was called. Seems to me like this could be a dangerous game to play and partial specializations would be a better fit for this kind of thing.. though, I'm no c++ expert.

The same incorrect result is achieved if I have two overloads, one with a const-reference and another with a const-pointer when I try to pass in a non-const-pointer the function that takes a const-reference is called. I could create two overloads that do not take const parameters but what if I didn't want the function accidentally changing the value of that variable passed to it (of course I would use const) but what if I need to pass a non-const pointer to the function that accepts a const-pointer.. silent disaster. I could probably cast the non-const pointer to const but this isn't really desirable.

Of course, these are all hypothetical needs, and I don't imagine I will come across anything like this in the near future, if ever, though it is still interesting and worth knowing.

I could probably cast the non-const pointer to const but this isn't really desirable.

Overloading to the rescue (how ironic...):

template <typename T> void function(T x)
{ ... }

template <typename T> void function(const T* x)
{ ... }

template <typename T> void function(T* x)
{ function(static_cast<const T *>(x)); }



Of course, these are all hypothetical needs, and I don't imagine I will come across anything like this in the near future, if ever, though it is still interesting and worth knowing.

Perhaps not in a near future, but they certainly aren't hypothetical. I would say that your example with just an overload for pointer type is a fairly trivial and not totally unexpected example. The rules for determining parameter match to disambiguate a function call, and how templates and overloading interact, can be quite important to know once you start overloading functions even the slightest bit.

This topic is closed to new replies.

Advertisement