zoecarver
zoecarver

Reputation: 6403

Multiple possible templates in a class

I am trying to have a class which can be created with either a type or an array. I am not sure if templates are the best way to do this but I thought they might work. In the below code example, I have a class which has two static methods who both return an instance of the class based on the template they are given:

template<class T>
template<class A, size_t N>
class Foo {
    static A[N] bar();
    static T bar();
}

template<class A, size_t N>
Foo<A[N]> Foo<A[N]>::bar();

template<class T>
Foo<T> Foo<T>::bar();

So I can call them like this:

Foo<int[5]> intarrthing Foo<int[5]>::bar();
Foo<int> intthing Foo<int>::bar();

This doesn't work because not all the templates are used so how could I implement something like this?

Upvotes: 0

Views: 50

Answers (1)

Jarod42
Jarod42

Reputation: 217145

Functions cannot differ only by return type (except functions template).

From your usage, you might simply do:

template<class T>
class Foo {
    static Foo<T> bar() { return {}; }
};


Foo<int[5]> intarrthing = Foo<int[5]>::bar();
Foo<int> intthing = Foo<int>::bar();

Upvotes: 2

Related Questions