Kerry
Kerry

Reputation: 115

C++ restricting types in generics (and pointer questions)

This question may have more to do with how C++ handles pointers at compile-time, but this came up while learning about generics. I have the following code (which doesn't give me any errors in Visual Studio):

class myClass { int x; };

template<typename T>
int myFunc(T obj)
{
    return obj.someMethod();
}

int main(int argc, char *argv[])
{
    myClass obj = myClass();
    myFunc(obj);
}

Obviously, "myClass" doesn't have someMethod(), but Visual Studio doesn't give me any errors. However, when I change myFunc to this:

template<typename T>
int myFunc(T *obj)
{
    return obj->someMethod();
}

I do get an error, and I think it's because the compiler checks that myClass doesn't have a someMethod(). Why don't I get the same error with the first block of code?

Upvotes: 0

Views: 60

Answers (1)

Hal
Hal

Reputation: 1139

Both passing by value and passing by reference using a pointer fail for me with g++ and clang++ clang++ is version 3.6.1 g++ is version 4.9.2

If you can reproduce this on visual studio, file a bug on their compiler.

Upvotes: 2

Related Questions