c++ - 使用constexpr返回函数值C++的模板函数调用

标签 c++ templates enums constants constexpr

这是我的代码:

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'
    }
};
尝试从somefunc的函数f调用struct B时,出现错误,提示'this cannot be used in a constant expression.'是我要执行的操作吗?

最佳答案

Is what I am asking for impossible to do?


是的,没有。 this是运行时值,实际上不能在常量表达式中使用。
但是在您的情况下,mytype()似乎不需要成为成员函数,因此可以将其声明为static
struct A {
    static constexpr MYENUM mytype() {
        return MYENUM::A;
    }
};
现在它将起作用。 (Demo)

关于c++ - 使用constexpr返回函数值C++的模板函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63522187/

相关文章:

c++ - 在 C++ 中创建一个全局对象数组

ruby-on-rails - Rails , 枚举角色

c++ 将枚举值标记为已弃用?

c++ - 在 C++ 中使用枚举值作为映射中的条目

c++ - 获取指针指向的对象

c++ - 强制崩溃应用程序

c++ - 放置新的和完美的转发

c++ - 使用 EIGEN_MATRIXBASE_PLUGIN 访问 Eigen 中的模板值

ios - 如何为 Xcode 自定义 ViewController 模板文件?

c++ - C++中有没有一种设计模式可以方便地以统一的函数接口(interface)查询不同类型的数据?