1

I was reading this question and some other stuff : Are there cases where a typedef is absolutely necessary??

I wrote this code :

const int arrayOfInt[10] = {0};

template<typename T, int N> using X = const T (&)[N];

struct foo
{
    template<typename T, int N> operator  X<int,10> () { return arrayOfInt;  }
};

void bar(const int (&) [10]) {}

int main()
{
    bar(foo());
    return 0;
}

using feature of c++11 is not working for me , also I'm unable to think how to typedef the return type in this case too since my class foo is not template itself. I need to see solution using using keyword and typedef both . Thanks a lot awesome peoples of SO :)

Community
  • 1
  • 1
Angelus Mortis
  • 1,534
  • 11
  • 25

2 Answers2

2

Since X is an alias template you need to provide the template arguments explicitly; they won't be captured from the surrounding scope:

struct foo
{
    template<typename T, int N> 
    operator X<T,N>() { return arrayOfInt; }
    //        ^^^^^
};

You can't do this with a typedef as there's no such thing as a typedef template.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • but I still get error "error: invalid initialization of reference of type 'const int (&)[10]' from expression of type 'foo' " – Angelus Mortis Dec 02 '15 at 12:22
1
template<typename T, int N> operator  X<int,10> () { return arrayOfInt;  }

template arguments T and N are never used and hence shall never be deduced.

Fixed Live On Coliru

const int arrayOfInt[10]{0};

template<typename T, int N> using X = T const (&)[N];

struct foo {
    template<typename T, int N> operator  X<T,N> () const { return arrayOfInt;  }
};

void bar(const int (&) [10]) {}

int main()
{
    foo f;
    X<int, 10> v = f;
    bar(foo());
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Thanks a lot but can you please explain in my code`template operator X () { return arrayOfInt; }` -> `X` doesn't changes the semantics of code from your corrected code, yet it produces error. Thanks – Angelus Mortis Jan 25 '16 at 09:54
  • What part of it do you replace? I don't see the difference. The problem is there is no way to _explicitly_ specify the arguments for `T` and `N` (afaik). – sehe Jan 25 '16 at 09:57
  • Awesome, now I realize my puny mistake. Thanks a lot sir :) – Angelus Mortis Jan 25 '16 at 09:59
  • Though when I try to call conversion function template explicitly I get baffling error -> `foo().operator X()` , so my last question, is it even possible to call conversion function template explicitly ? – Angelus Mortis Jan 25 '16 at 10:02
  • Yes, [it's impossible](http://stackoverflow.com/questions/34039828/template-conversion-operator-returing-reference-to-array/34989172#comment57707371_34989172). However if you have to (a) you have other problems :) (b) it's easily fixed (by creating the non-operator template member and implementing one in terms of the other) – sehe Jan 25 '16 at 10:15