Azmisov Azmisov - 17 days ago 6
C++ Question

Allow class to be assigned as zero

I'm writing a template function, and I want to initialize a template variable to zero. I was thinking of setting the variable equal to zero, and then let the class type define its own definition of "zero":

T data = 0;


I tried overloading the assignment operator:

class Example{
public:
int data;
Example(){}
Example& operator=(int v){
data = v;
return *this;
}
};

template <class T> T test(){
T data = 0;
return data;
}

int main(int argc, char** argv){
double v1 = test<double>();
Example v2 = test<Example>();
return 1;
}


... but the compiler gives me "error: conversion from 'int' to nonscalar type...". How can I make this work? or is there a better way of doing what I'm trying to do?

Answer

The problem with your code is that T data = 0; actually calls a constructor, not operator=. So in order your code to work, you need to declare a constructor accepting an int.