Ruggero Turra
Ruggero Turra

Reputation: 17670

automatic template argument deduction not working

Why do I get:

missing template arguments before ‘(’ token

when using:

sort(index_mu.begin(), index_mu.end(), index_cmp(mu_pt_corrected));

where index_mu is std::vector<int> and mu_pt_corrected is std::vector<float>

template<class T> struct index_cmp {
    index_cmp(const T arr) : arr(arr) {}
    bool operator()(const size_t a, const size_t b) const
    { return arr[a] > arr[b]; }
    const T arr;
};

isn't the compiler able to undestant the type of T? Why?

Upvotes: 1

Views: 285

Answers (1)

James Kanze
James Kanze

Reputation: 153889

Template argument deduction only applies to functions. In general, the compiler won't have the necessary information to deduce the arguments for a class. For this reason, it's common in such cases to add a function along the lines of:

template <typename T>
index_cmp<T>
indexCmp( T const& arr )
{
    return index_cmp<T>( arr );
}

You can then call:

sort( index_mu.begin(), index_mu.end(), indexCmp( mu_pt_corrected ) );

The compiler will deduce the type of the function, which in turn defines the type.

Upvotes: 4

Related Questions