0

I have struct with template parameter which created for enum. But i don`t know right way to create object correctly.

#include <iostream>

enum values
{
    n1 = 1,
    n2 = 2,
    n3 = 3
    //
};

int f(int n1, int n2, int n3)
{
    int some_int;
    //...
    return some_int;
}

struct MyClass
{

    int num;

    template<typename E>
    MyClass() : num(f(E::n1, E::n2, E::n3))
    {

    }
    //...
};

int main()
{
    //???
}

Note: By design i cannot use class level templates

Kri
  • 111
  • 2
  • 9
  • 2
    Do you want an instantiated `MyClass` to be parameterized on a specific value that will always be from `values`, or on altogether separate enums? In other words, do you want `MyClass()` or `MyClass();` – alter_igel Aug 16 '18 at 20:38
  • I need MyClass object; (or other enum type) but in C++ it is not working – Kri Aug 16 '18 at 20:48
  • Can you show what you would accomplish with that? We might be able to help you with a work around. – NathanOliver Aug 16 '18 at 20:52
  • @NathanOliver sure. code is updated. please welcome. i have field in the class which value creates by some function. When i am create object i need create it with different values from enum. Sure, i can pass that arguments directly but as result i have not readable code because now parameters count is 5 – Kri Aug 16 '18 at 21:04
  • @Kri You could use something like [this](https://stackoverflow.com/a/13002706/4342498) in order to be able to get the template to be deduced for you. It would make the call something like `MyClass foo{TypeCarrier{}};` – NathanOliver Aug 16 '18 at 21:08
  • @NathanOliver OK thank you! Is there an overhead in this code? – Kri Aug 16 '18 at 21:13
  • There shouldn't be. – NathanOliver Aug 16 '18 at 21:15
  • @NathanOliver ok thanks again – Kri Aug 16 '18 at 21:17
  • You could even do something like what the C++17 standard library does with `inline constexpr` variables `std::in_place` used as a tag argument to a `std::any` constructor, and thus eliminate the inner pair of braces. e.g. `MyClass foo{enum_type_is};` – Daniel Schepler Aug 16 '18 at 21:28
  • @NathanOliver as i understand there we are create object of incomplete type MyClass foo{TypeCarrier{}};. is there an UB? Or it is unevaluated context and code is correct? – Kri Aug 16 '18 at 21:52
  • No object of incomplete type is being created. You just don't actually use the function parameter that the constructor declares: http://coliru.stacked-crooked.com/a/b02e272bad9356aa – NathanOliver Aug 16 '18 at 21:56
  • @NathanOliver Thanks. I see you are use braced initialization in this example, can you please explain why? I have get error when use () instead of {} – Kri Aug 16 '18 at 22:06

0 Answers0