Maximilian Mordig
Maximilian Mordig

Reputation: 1399

template typedef C++11

I was trying to use C++11's "using =" syntax to typedef a templated comparison function. I then define a templated-function and want to assign it to comparisonFunc of type "ComparisonFunction".

  template<typename ValueType> using ComparisonFunction = bool (*)
                 (ValueType const & val1, ValueType const & val2);

    template<typename ValueType>
    bool equalFunction(ValueType const & val1, ValueType const & val2) {
        return val1==val2;
    }

    template<typename ValueType>
    ComparisonFunction<ValueType> comparisonFunc = equalFunction<ValueType>;   //Error is here

    int main()
    {

    }

The first few lines work, but declaring equalFunc (without even giving a value to it) gives the error

error: template declaration of 'bool (* equalFunc)(const ValueType&, const ValueType&)

All I found on this error was related to C++03 where no "using =" syntax exists.

Thanks in advance

Upvotes: 1

Views: 184

Answers (2)

aschepler
aschepler

Reputation: 72271

Your declaration

template<typename ValueType>
ComparisonFunction<ValueType> comparisonFunc = equalFunction<ValueType>;

is a variable template, since the declaration is for the variable comparisonFunc, not a type or function. C++14 allows variable templates, but there is no such thing in C++11.

Upvotes: 3

user3920237
user3920237

Reputation:

Since you require a different function pointer for each instantiation of equalFunction, you can make ComparisonFunction a functor. As you said, template aliases don't exist in C++03 so your final code is:

template<typename ValueType>
bool equalFunction(ValueType const & val1, ValueType const & val2) {
    return val1==val2;
}

template <typename ValueType>
struct ComparisonFunction
{
    bool operator()(ValueType const & val1, ValueType const & val2)
    {
        return equalFunction(val1, val2);
    }
};

Upvotes: 0

Related Questions