【问题标题】:How to avoid writing explicit template arguments for an operator taking a compile-time value?如何避免为获取编译时值的运算符编写显式模板参数?
【发布时间】:2013-04-30 00:17:28
【问题描述】:

根据我之前的帖子,我了解到我不能将函数参数用作编译时构造的参数。这是因为函数的参数是在运行时需要的,但模板参数是在编译时处理的。

因为我很遗憾不能在参数上使用constexpr,所以我决定使用模板参数。它工作得很好,但就外观而言,我不会说它是最好的选择:

#include <tuple>

template <class... Args>
struct type_list
{
    std::tuple<Args...> var;

    type_list(Args&&... args) : var(std::forward<Args>(args)...) {}

    template <std::size_t N>
    auto operator[](std::size_t)
        -> typename std::tuple_element<N, std::tuple<Args...>>::type&&
    {
        return std::move(std::get<N>(var));
    }
};

int main()
{
    type_list<int, int, bool> list(2, 4, true);

    int i = list.operator[]<0>(0); // How can I avoid this?
}

有什么办法可以避免这种情况吗?如何在避免显式运算符语法的同时为函数提供常量表达式?可以用宏吗?

【问题讨论】:

  • 直接使用元组和std::get有什么问题吗?

标签: c++ templates c++11 variadic-templates


【解决方案1】:

您可以添加一个包装编译时常量的类模板(或使用这个http://www.boost.org/doc/libs/1_53_0/libs/mpl/doc/refmanual/int.html),将运算符 [] 的参数模板化,并将包装常量的值传递给运算符。您的运营商的声明更改为:

template <typename T>
auto operator[](T) -> ...

如果使用 boost MPL,则在运算符内部将 N 替换为 T::value

操作符的使用改为:

int i = list[int_<0>()];

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多