三重嵌套模板参数的 C++ 正确语法

标签 c++ templates

我很困惑为什么下面的代码会被编译器拒绝。请帮忙?

template<template<template<class> class> class Ptr,
template<class> class Container, class T>
inline void print(Ptr<Container<T>> l) {
    std::cout << '[';
    for (auto it = l->begin(); it != l->end() - 1; ++it) {
        std::cout << *it << ", ";
    }
    std::cout << l->back() << ']' << std::endl;
}

最佳答案

我对@RSahu 的回答中哪些有效,哪些无效以及它是否能解决一般问题感到困惑。

但是,受其启发,我得到了以下解决方案。这只是利用了类模板类可以是可变的这一事实。例如现在与 std::vector<T, A> 兼容或其他具有或多或少模板参数的类(希望是容器)。事实上,对 Ptr 做同样的事情很有用。参数,因此它也与 std::unique_ptr 兼容需要比 std::shared_ptr 更多的模板参数.

http://coliru.stacked-crooked.com/a/40d43526ed77eb9d

#include <iostream>
#include <vector>
#include <memory>

template<template<class...> class Ptr, template<class...> class Container, class T>
inline void f(Ptr<Container<T>> p) {
    std::cout << "bla" << std::endl;
}

int main() {
    f(std::make_shared<std::vector<int>>());
}

注意:话虽如此,我认为有比强制模式更好的方法来约束参数类型。

例如,这可能是一个替代方案:

template<class PtrContainerT, typename = decltype( std::declval<PtrContainerT>()->back())> //probably pretty much constrains the intended use
inline void f(PtrContainerT&& p) {
    using T = typename PtrContainerT::element_type::value_type; //in case you need to know T
    std::cout << "bla" << std::endl;
}

http://coliru.stacked-crooked.com/a/fbe43aab94364764

甚至更重要(尽管不是 100% 等效):

template<class PtrContainerT, typename T = typename PtrContainerT::element_type::value_type> //probably pretty much constrains the intended use
inline void f(PtrContainerT&& p) {
    std::cout << "bla" << std::endl;
}

使用 std::decay<PtrContainerT>::...etc如有必要。

关于三重嵌套模板参数的 C++ 正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31768769/

相关文章:

c++ - yyparse() 未在 Bison/Flex C++ 项目中仅针对某些版本的 gcc/bison/flex 声明

c++ - 当调用 Visual Studio 2008 的 build->clean/build->rebuild 时,如何添加另一个删除扩展?

c++ - 为什么将 NULL 发送给 std::cout 输出后完全消失

c++ - typedef 以下类型 : Pointer to a member function Fof "any" class having a member function F

c++ - 为 void 类型部分特化参数包参数的语法是什么?

C++让我大吃一惊

c++ - 开源 VoIP/SIP Windows C API

c++ - if constexpr std::is_same 在 VS 2022 下

email - 为什么 Magento 没有为交易电子邮件订单提取我的主题模板文件?

C++ - 可访问性与可见性