使用方法参数进行元编程 [英] Meta-Programming with a Method Parameter

查看:139
本文介绍了使用方法参数进行元编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个包装器。出于这个问题的目的,它可以简化为:

I'm writing a pair wrapper. For the purposes of this question it can be simplified down to:

using namespace std;

template <class T1, class T2>
class myPair {
    pair<T1, T2> member;
public:
    myPair() = default;
    myPair(T1 x, T2 y) : member(make_pair(x, y)) {}
};

我希望能够处理 myPair 作为一个大小为2的可索引容器。为此,我显然需要为 myPair 编写索引运算符。我想做类似的事情,但我的返回类型将取决于方法参数,我不能在元编程中使用方法参数。

I'd like to be able to treat a myPair as an index-able container of size 2. To do this I'd obviously need to write an index operator for myPair. I'd like to do something like this, but my return type will depend upon a method parameter, and I can't use method parameters in meta-programming.

auto myPair::operator[](int index) {
    static_assert(index >= 0 && index < 2, "Index out of range");

    return get<index>(*this);
}

显然我可以像一样解决这个问题对通过提供 get 函数来完成,但我希望能够使用索引运算符语法。有什么方法可以专门化一个函数模板或使用方法参数来元编程模板的返回类型吗?

Obviously I could tackle this in the same way that pair does by providing a get function, but I'd like to me able to use the index operator syntax. Is there any way I can specialize a function template or use a method parameter to meta-program a template's return type?

推荐答案

它是几乎可能。整数文字不能直接用作常量表达式,但可以包装在一个中,例如模板实例化。

It's almost possible. The integer literal can't be used directly as a constant-expression, but it can be wrapped in one, for example a template instantiation.

template <int> struct idx_ {};

template <char... C>
auto operator ""_i () {
    return idx_<(C - '0')...>{};
}

template <class T1, class T2>
class myPair {
    std::pair<T1, T2> member;
public:
    myPair() = default;
    myPair(T1 x, T2 y) : member(std::make_pair(x, y)) {}

    T1 &operator [] (idx_<0>) {
        return member.first;
    }

    T2 &operator [] (idx_<1>) {
        return member.second;
    }
};

int main() {
    myPair<int, std::string> mp(42, "Hi");
    std::cout << mp[0_i] << ", " << mp[1_i] << '\n';
}

输出:

42, Hi

住在Coliru上

这篇关于使用方法参数进行元编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆