c++ - 强制非推断上下文-type_identity等

标签 c++ templates template-argument-deduction type-deduction

我正在尝试制作一个模板,该模板可以推导与一个模板参数关联的类型,同时在非推导上下文中处理其他类型。下面提供了一个最小的示例。我可以使用两个演绎上下文来完成我要寻找的东西,但是可以一次完成吗?我以为我会尝试使用类似type_identity的方法,但是我没有任何运气。
实时示例:https://onlinegdb.com/By0iDOM-P

template<size_t... Idx, size_t s>
void foo(index_sequence<Idx..., s>) {
    cout << s << endl;
}

template<typename T>
struct TypeIdentity {
    using Type = T;
};

template<typename T>
using Identity = typename TypeIdentity<T>::Type;

template<typename... Idx, size_t s>
void bar(index_sequence<Identity<Idx>{}..., s>) {
    cout << s << endl;
}

template<size_t s>
void baz(index_sequence<0, s>) {
    cout << s << endl;
}

template<size_t... Idx>
struct Qux {
    template<size_t s>
    static void qux(index_sequence<Idx..., s>) {
        cout << s << endl;
    }
};

int main()
{
    foo<0>(make_index_sequence<2>{}); // couldn't deduce template parameter ‘s’
    bar<integral_constant<size_t, 0>>(make_index_sequence<2>{}); // couldn't deduce template parameter ‘s’
    baz(make_index_sequence<2>{});
    Qux<0>::template qux(make_index_sequence<2>{});

    return 0;
}

最佳答案

否。问题在于Idx...包过于贪婪,无法为s保留任何内容。您可以使用s, Idx...来获取第一个值,但是不能使用Idx..., s来获取最后一个值。 TypeIdentity不能帮助您做到这一点,您还需要其他技巧。
例如,解压缩为数组(C++ 14):

template<std::size_t first, std::size_t... rest>
void foo(std::index_sequence<first, rest...>) {
    const std::size_t indices[]{first, rest...};
    const std::size_t last = indices[sizeof...(rest)];

    std::cout << last << std::endl;
}
或将fold expressioncomma operator(C++ 17)结合使用:
template<std::size_t first, std::size_t... rest>
void foo(index_sequence<first, rest...>) {
    const std::size_t last = (first, ..., rest);
    std::cout << last << std::endl;
}
我隔离了first以确保整个包first, rest...永远不会为空。

关于c++ - 强制非推断上下文-type_identity等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63201976/

相关文章:

c++ - 推导模板化类参数的模板参数 : const issue

c++ - 模板模板参数的显式匹配

c++ - 如何在 C++ 中编写基本类型(float)的直接替换来覆盖运算符==?

c++ - 为什么 c++ 程序员使用 != 而不是 <

c++ - unique_ptr 列表,用于派生模板类

python - Django 查看模板的默认值

c++:何时传递指针与返回对象

c++ - 用 C++ 发出声音(哔)

c++ - 在类声明之前在模板内进行 `using` 声明

c++ - 我可以在不提供参数的情况下生成函数吗?