jeudi 9 mars 2017

Check at compile time if a template argument type is set or multiset, and element type of the container is arithmetic

I have a function named 'equal' accepting 2 parameters, each of them should be either std::set or std::multiset, and the element type of container should be arithmetic type (int, float, double ... ). I want the compiler report an error if above 2 conditions not satisfied.

I hope my code could run like this:

int main(void)
{
    std::set<int> s1;
    std::set<int> s2;
    equal(s1, s2);    //  OK

    std::multiset<float> s3;
    std::multiset<float> s4;
    equal(s3, s4);    //  OK

    std::set<int> s5;
    std::multiset<int> s6;
    equal(s5, s6);    //  compile error

    std::set<int*> s7;
    std::set<int*> s8;
    equal(s7, s8);    //  compile error

    std::vector<int> s9;
    std::vector<int> s10;
    equal(s9, s10);    //  compile error

    return 0;
}

And now it can check if element is arithmetic type, like below:

template <class Container, class = typename std::enable_if<std::is_arithmetic<typename Container::value_type>::value>::type>
bool equal(const Container &container1, const Container &container2)
{
    return true;
}

But how to make sure the container only be set or multiset ?

the compiler can support C++11, such as vc2015 or gcc4.8

Aucun commentaire:

Enregistrer un commentaire