3

How can I make a template constant value of any type to be accepted in C++? Example:

using namespace std;
typedef enum { E11, E12} E1;
typedef enum { E21, E22} E2;

void a(E1 e) { cout<<"something from E1"<<endl; }
void a(E2 e) { cout<<"something from E2"<<endl; }

template <typename T, T Element>
class Foo {
    public:
        void foo() {
            a(Element);
        };
};

// Unwanted "solution" using #define
#define _Foo(x) Foo<decltype(x), x>

int main() {
    Foo<E1, E12> d1;
    d1.foo();
    Foo<E2, E22> d2;
    d2.foo();
    
    // using define-solution
    _Foo(E12) d3;
    d3.foo();
    _Foo(E22) d4;
    d4.foo();
}

See the hacky solution using define, but what I really want is:

template <AnyTypeAcceptor Element>
class Foo {
    public:
        void read() {
            a(Element);
        };
};

int main() {
    Foo<E22> d1;
    d1.read();
    
    Foo<E11> d2;
    d2.read();
}

As you can see above with the define solution all the information necessary is definitely here at compile time but I suspect there is no solution in C++?

knight37x
  • 53
  • 6
  • 1
    `template ` – user7860670 Feb 02 '23 at 12:53
  • 4
    You want an [`auto` template parameter](https://en.cppreference.com/w/cpp/language/template_parameters), which are available since C++17. If you're limited to C++14 or below, there is no solution. – Quentin Feb 02 '23 at 12:53
  • oh thanks I actually tried auto template parameter, but it didn't work in my used online compiler as I missed to switch to a newer version. – knight37x Feb 02 '23 at 14:47
  • Near duplicate of [c++ - Passing any function as template parameter - Stack Overflow](https://stackoverflow.com/questions/24185315/passing-any-function-as-template-parameter) (except that in this case it's "any type" instead of "function type" but essentially pretty-much the same. See also the linked question there [c++ - Advantages of auto in template parameters in C++17 - Stack Overflow](https://stackoverflow.com/questions/38026884/advantages-of-auto-in-template-parameters-in-c17) – user202729 Feb 03 '23 at 11:10

0 Answers0