访问模板化容器中的成员函数

时间:2017-12-07 01:25:36

标签: c++ templates struct

我希望能够<< val.first()val.second()元素 struct Data<std::pair<F, S>FS应该是通用的,因为它们可以是struct Data<int>(特定类型)之类的任何指定。我不知道如何编写struct Data<std::pair<F, S>模板的方式,只允许struct Data作为FS

#include <fstream>
#include <iostream>
#include <sstream>
#include <utility>

template <typename T>
struct Data;

template <typename T>
std::ostream& operator<<(std::ostream& os, const Data<T>& val) {
    return val(os);
}

template <typename T>
Data<std::remove_cv_t<T>> data(const T& val) { return { val }; }

template <>
struct Data<int> {
    std::ostream& operator()(std::ostream& os) const {
        os << val;
        return os;
    }
    const int& val;
};

//More struct Data for templatized types for other specific types


template <typename F, typename S>
struct Data<std::pair<F, S> > {
    std::ostream& operator()(std::ostream& os) const {
        os << data(val.first()) << data(val.second());
        return os;
    }
    std::pair<F, S> val;
};

//More struct Data templatized for other container types

测试时的错误是:

 error: called object type 'int' is not a function or function pointer
                    os << data(val.first()) << data(val.second());
                               ^~~~~~~~~

1 个答案:

答案 0 :(得分:0)

firstsecond是std :: pair的两个(公共)成员变量,它们不是成员函数。

os << data(val.first()) << data(val.second());

变为

os << data(val.first) << data(val.second);