【问题标题】:Conditional branching in C++ templatesC++ 模板中的条件分支
【发布时间】:2018-03-17 23:11:36
【问题描述】:

这个函数模板应该使用索引函数从一个元组返回X类型的第一个元素,但它不会编译。

template<class X, class F, class... R>
constexpr X getByType(tuple<F, R...> t) {
    if (is_same<F,X>::value) {
        return get<0>(t);                //ERROR POSITION
    }
    if (sizeof...(R) == 0) {
        throw 4;
    }
    return get_vector<X>(tail(t));
}

int main() {
    int i = get<int>(make_tuple(4.2,"assaaa",4));
}

编译器说它不能将 double 类型转换为 int。这个元组的第一个元素是一个双精度。我猜原因是 if 条件要在运行时进行评估。如何在编译时执行元组第一个元素的条件返回?

【问题讨论】:

标签: c++ templates metaprogramming template-meta-programming


【解决方案1】:

如果你的编译器不支持constexpr-if,你需要将一些逻辑分解到帮助器struct中。

示例实现(当然可以更高效地实现):

template<class X, class... List>
struct find_first;

template<class X, class... List>
struct find_first<X, X, List...> { static const int value = 0; };

template<class X, class Y, class... List>
struct find_first<X, Y, List...> { static const int value = find_first<X, List...>::value + 1; };

template<class X, class... R>
constexpr X getByType(tuple<R...> t) {
    return get<find_first<X,R...>::value>(t);
}

Wandbox-Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2014-07-01
    相关资源
    最近更新 更多