expl0it3r
expl0it3r

Reputation: 335

Template function call with constexpr return function value C++

Here is my code :

enum class MYENUM {
A = 0, B = 1
};

template<MYENUM T>
void somefunc() {
    std::cout << "working" << std::endl;
}
struct A {
    constexpr MYENUM mytype() {
        return MYENUM::A;
    }
};
struct B {
    A obj;
    void f() {
        somefunc<obj.mytype()>(); //'this cannot be used in a constant expression'
    }
};

In trying to call somefunc from the function f from struct B, I get an error saying 'this cannot be used in a constant expression.' Is what I am asking for impossible to do?

Upvotes: 1

Views: 89

Answers (1)

rustyx
rustyx

Reputation: 85481

Is what I am asking for impossible to do?

Yes and no. this is a run-time value, and indeed cannot be used in a constant expression.

But in your case it seems mytype() doesn't need to be a member function, so you can declare it static.

struct A {
    static constexpr MYENUM mytype() {
        return MYENUM::A;
    }
};

Now it will work. (Demo)

Upvotes: 4

Related Questions