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?

3
  • Why do you need a template in this case at all? Commented Dec 2, 2014 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? Commented Dec 2, 2014 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. Commented Dec 2, 2014 at 14:15

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

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 Ah, So you're creating a "Function Template" here. "The format for declaring function templates with type parameters is: template <class identifier> function_declaration or template <typename identifier> function_declaration You choose the identifier but the rest of the definition must follow that format. template <MyClass name> does not follow that format.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.