【问题标题】:c++ class member variable as a non type template argument, and how to use it?c++类成员变量作为非类型模板参数,如何使用?
【发布时间】:2021-07-19 02:29:50
【问题描述】:

我有以下用例,

struct Trans {
         double price;
};
struct Quote {
    double bid_price_1;
    double ask_price_1;
};
template<typename DataT, double DataT::*ptr>
class Return {
public:
    void operator()(DataT& data) {
        // print out the right field of the right class
        //std::cout << &DataT::ptr << std::endl;
    }
};
int main() {
    Quote quote {1, 2};
    Return<Quote, &Quote::bid_price_1> ret;
    ret(quote);
}

Return类的operator中,我希望能够引用正确类的正确成员变量,我看了下面的帖子(Pointer to class member as template parameter),但是好像没有提到如何检索成员变量部分。我想知道检索编译时指定的成员变量的正确语法是什么。

【问题讨论】:

  • 您在寻找(data.*ptr)吗?
  • @IgorTandetnik 是的,谢谢。

标签: c++ templates


【解决方案1】:

寻址成员的语法使用运算符.*(用于引用)和-&gt;*(用于指针)。你的情况

void operator()(DataT& data) {
    std::cout << data.*ptr << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2011-07-06
    相关资源
    最近更新 更多