0

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?

zoecarver
  • 5,523
  • 2
  • 26
  • 56
  • Identifiers starting with an underscore and an uppercase character are reserved for use by the standard C++ library. – Sam Varshavchik Jan 28 '19 at 23:56
  • Please note that symbols beginning with an underscore followed by an upper-case letter (like e.g. `_Tp` or `_A_tp`) are reserved in all scopes for the implementation (compiler and standard library). Please see [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier) for details. – Some programmer dude Jan 28 '19 at 23:56
  • Sorry about that. I can update my question. Thanks for the link @Someprogrammerdude – zoecarver Jan 28 '19 at 23:57
  • How doesn't work? What errors do you see? The first two lines also look suspicious having a `template` of a `template`. – Ken Y-N Jan 28 '19 at 23:59
  • What is it that you're actually trying to achieve? – Lightness Races in Orbit Jan 29 '19 at 00:10
  • I'm not entirely certain exactly what you're trying to do. But note that if you define a `template class Foo`... using just `T` and then use `Foo`, then the parameter `T` *is* an array type within the `Foo` definition. – aschepler Jan 29 '19 at 00:11
  • I wanted to be able to have two different functions for the different templates (handle arrays differently from "normal" types). What you suggested works completely fine. – zoecarver Jan 29 '19 at 00:12

1 Answers1

2

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();
Jarod42
  • 203,559
  • 14
  • 181
  • 302