I'm a bit confused about partial template specialization... I have some code that depends on an arithmetic data type T, and on a small integer DIM. I want to be able to specify different class methods for different values of DIM. The impossibility of using partial template specialization led me to explore enable_if. It's exactly what I needed... except I want it to return a number and not a type. How can I do that? The following code should illustrate what I want.
#include <stdio.h>
#include <iostream>
#include <type_traits>
template <typename T, int DIM>
class foo{
public:
T function();
};
template <typename T, int DIM>
T foo<T, std::enable_if<DIM == 1>::value>::function(){
// do something
return 1.0;
}
template <typename T, int DIM>
T foo<T, std::enable_if<DIM == 2>::value>::function(){
// do something else
return 2342.0;
}
int main(){
foo<int, 1> object;
int ak = object.function();
std::cout << ak << "\n";
return 0;
}
U
andD
) to activate SFINAE: it's enough a template parameter involved in thestd::enable_if
test. So should work simply astemplate <int D = DIM, typename std::enable_if<D == 1>::type* = nullptr> T function()
(andvoid
is the default returned type forstd::enable_if
– Yellowish