简体   繁体   English

C ++模板中的条件分支

[英]Conditional branching in C++ templates

This function template is supposed to return the first element of type X from a tuple using the indexing function, but it won't compile. 该函数模板应该使用索引函数从元组返回类型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));
}

The compiler is saying that it can't cast a double to an int. 编译器说不能将double转换为int。 The first element of this tuple is a double. 该元组的第一个元素是一个double。 I guess the reason being the if condition is left to be evaluated at runtime. 我想原因是在运行时是否需要评估if条件。 How can I perform the conditional return of the first element of tuple at compile time? 如何在编译时执行有条件返回元组的第一个元素?

In case your compiler does not support constexpr-if , you need to factor out some logic into a helper struct . 如果您的编译器不支持constexpr-if ,则需要将一些逻辑分解为helper struct

Example implementation (could certainly be implemented more efficient): 示例实现(肯定可以更高效地实现):

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 魔盒演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM