0

This following doesn't work:

// case one:

struct MyClass {
    int x;
};

template <MyClass name>
void foo() {
}

But if I make it a reference it works:

// case two:

struct MyClass {
    int x;
};

template <MyClass &name>
void foo() {
}

Do I need to pass a constant object of MyClass for it work with class in case one?

user963241
  • 6,758
  • 19
  • 65
  • 93
  • Why do you need a template in this case at all? – πάντα ῥεῖ Dec 02 '14 at 12:20
  • @πάνταῥεῖ: I'm asking the reason why it is not allowed.. if you could comment on it please since the question is already closed. Like I know that templates are deduced at compile time but how exactly class objects are a problem? – user963241 Dec 02 '14 at 13:23
  • The 2nd answer in the duplicate describes it very well why it's not allowed to use a class type vs a pointer or reference to class. – πάντα ῥεῖ Dec 02 '14 at 14:15

1 Answers1

1

Looks like you're trying to specialize a template?

Perhaps this is what you want?

template <typename T>
void foo(const T& param){
    cout << reinterpret_cast<const int&>(param) << endl;
}

template <>
void foo(const MyClass& param) {
    cout << param.x << endl;
}

int main() {
    MyClass bar = {13};

    foo(42L); // Outputs 42
    foo(bar); // Outputs 13

    return 0;
}

(Please be aware that reinterpret_cast is highly suspect, I just used it for an example here.)

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • No, I only want to know what goes wrong if I use a class object instead of a reference to it. Does it have to do with because templates are deduced at compile time? How exactly? – user963241 Dec 02 '14 at 13:24
  • @user963241 Ah, So you're creating a ["Function Template"](http://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Function_templates) here. "The format for declaring function templates with type parameters is: `template function_declaration` or `template function_declaration` You choose the `identifier` but the rest of the definition must follow that format. `template ` does not follow that format. – Jonathan Mee Dec 02 '14 at 13:31