mercredi 14 septembre 2016

Specialize same operator for different traits

I want to do the following with specialization by traits.

  1. Array Aa = Scalar in_a would use overloading I.

  2. Array Aa = Array Bb would use overloading II.

In the following code, overloading II never get used.

Someone mentioned that T1 cannot be deduced in overload II.

How to fix that?

Thanks.

#include <iostream>
using namespace std;
class A; // forward declaration.

template <typename T>
struct is_A : false_type {};
template <> struct is_A<A> : true_type {};

template <typename T>
struct is_int : false_type {};
template <> struct is_int<int> : true_type {};

class A{
    public:
        int val;
        void print(void){
            std::cout << val << std::endl;
        }
        template <typename T1>
        enable_if<is_int<T1>::value,void>
        operator=(T1 & input){
            val = 2*input; //Overload I
        }
        template <typename T1>
        enable_if<is_A<T1>::value,void>
        operator=(A & Bb){
            val = 5*Bb.val; //Overload II
        }
};

int main(void){
    A Aa;
    A Bb;
    int in_a = 3;
    Aa = in_a;
    Bb = Aa; //Actually Overload I instead of Overload II
             //is used. This leads to an error.
    Aa.print(); //This should give 6. (3x2)
    Bb.print(); //This should give 30. (6x5)
}

Aucun commentaire:

Enregistrer un commentaire