Reputation: 129
I am trying to understand the below code snippet
template <typename T>
class testopaque {
public:
void test(T var = T()) {}
};
How does the default argument work when called with a pointer type example int *
int main() {
testopaque<int *> obj1;
obj1.test();
}
what would the compiler generate when obj1.test() is called. I get a compiler error when I try
int main() {
int * var = int *();
}
error: expected primary-expression before ‘int’
int * ptr = int *();
Upvotes: 12
Views: 573
Reputation: 275200
Suppose you have x=1+2
. Would you expect x*3
, which is 9, to equal 1+2*3
, which is 7?
A similar problem is happening here. int*()
isn't the same as T=int*
then T()
.
Try (int*){}
, which solves the combined parsing and precident problems. Or using T=int*; int* x=T();
, or even int*x={};
(Simply using (int*)()
doesn't solve the problem due to how types are parsed, which is probably something you don't want to go too deeply into if you value your sanity.)
Upvotes: 10
Reputation: 118292
This is an example of how C++'s complicated syntax and grammar just produces unexpected results:
int *();
Your C++ compiler is very tempted to interpret this construct as a "function returning a pointer to an int
". Your C++ compiler gives in to this temptation, with the observed results.
You need to teach your C++ compiler what you're trying to accomplish here:
typedef int *intp;
int main()
{
int * var = intp();
}
Upvotes: 8
Reputation: 62472
When you use an expression like:
T var = T();
Where T
is a pointer type then var
will be assigned nullptr
Upvotes: 6