Template function which accepts only certain template parameters

Hi have been thinking that is it possible to have template classes with template functions such that functions only accept certain types. I mean that, if I have a template class

1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename A>
test_class {
public:
  template<typename B,class C>
  void test_function(B &b, std::vector<C> &c);
};

template<typename A>
template<typename B, class C>
void test_class<A>::test_function(B &b, std::vector<C> &c){
    // Do something with real numbers, but this doesn't 
    // compile with complex numbers
}


where test_function only works with real floating point numbers ( B = double, float or long double ) but it doesn't work with complex numbers. ( B = std::complex<double>, std::complex<float> or std::std::complex<long double> ) However, I might call this test_function somewhere else in the code also with complex numbers and then it should not do anything! I want that this function is compatible with my other functions, classes and so on. That is why I want to do this.. Any help is greatly appreciated!

-Ikaros
You should use the std::enable_if mechanism to do that.
http://en.cppreference.com/w/cpp/types/enable_if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <type_traits>

template<typename A>
class test_class {
public:
    template<typename B>
    void test_function(const B &b, typename std::enable_if<std::is_floating_point<B>::value, B>::type* = 0);
};

void main()
{
    test_class<int> t;
    // these compile
    t.test_function(0.f);
    t.test_function(0.0);
    // these don't
    t.test_function(0);
    t.test_function('c');
    t.test_function(t);
}


Hope this helps :)
You could also use the version that doesn't modify the function signature (see foo3 example in the link I sent) - but this doesn't work in my MSVS2010. If your compiler supports default parameters for function template arguments - then go for it.
Topic archived. No new replies allowed.