简体   繁体   中英

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM