Reputation: 53
I defined a templated class (DataArray<T>
) and I want to define a min()
function to compute the minimum value of integral type array (double
, float
, int
, ...) or complex type array (std::complex<double>
, std::complex<float>
, ...).
I am attempting to use type traits to select the correct function. Despite of the excellent discussion here, my code does not compile:
DataArray<double> and DataArray<std::complex<double>>: no matching overloaded function
What is the problem? Here is the minimal part of my code:
#include <iostream>
#include <vector>
#include <complex>
#include <type_traits>
template <typename T>
class DataArray {
public:
DataArray(T * data) : m_data(data) {}
template<typename T>
using isComplex = std::is_same<T, std::complex<typename T::value_type>>;
template <typename T>
typename std::enable_if<isComplex<T>::value>::type min() {
std::cout << "Min for complex" << std::endl;
}
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value>::type min() {
std::cout << "Min for arithmetic values." << std::endl;
}
private:
T * m_data;
};
int main()
{
double v1[2] ={ 1., 2.};
DataArray<double> d1(v1);
d1.min(); // min function for double : **compilation error**
std::complex<double> v2[2] = { { 1, 2 },{ 3, 4 } };
DataArray<std::complex<double>> d2(v2);
d2.min(); // min function for complex<double> : compilation error
}
Upvotes: 5
Views: 335
Reputation: 173014
The template parameter T
of member templates shadows the template parameter T
of class template. Give them another name; and specify default value for template parameter of min()
, otherwise they can't be deduced. e.g.
template<typename X>
using isComplex = std::is_same<X, std::complex<typename X::value_type>>;
template <typename X = T>
typename std::enable_if<isComplex<X>::value>::type min() {
std::cout << "Min for complex" << std::endl;
}
template <typename X = T>
typename std::enable_if<std::is_arithmetic<X>::value>::type min() {
std::cout << "Min for arithmetic values." << std::endl;
}
Upvotes: 4