首页 > 解决方案 > 模板化模板参数 U不识别 const 限定符

问题描述

我正在研究以下代码(没有真正的应用程序,只是出于好奇):

#include <memory>

template <typename T>
struct MyClass{};

template <template <class> class U, class T>
void foo(std::shared_ptr<U<T>> t){ }

template <class U>
void bar(std::shared_ptr<U> t){ }

int main()
{        
    std::shared_ptr<const MyClass<int>> ptr_to_const;
    std::shared_ptr<MyClass<int>> ptr;

    foo(ptr_to_const); // error
    foo(ptr); // OK

    bar(ptr_to_const); // OK
    bar(ptr); // OK
}

但是,编译器失败了

<source>: In function 'int main()':
<source>:17:9: error: could not convert 'ptr_to_const' from 'shared_ptr<MyClass<[...]>>' to 'shared_ptr<MyClass<[...]>>'
   17 |     foo(ptr_to_const); // error
      |         ^~~~~~~~~~~~
      |         |
      |         shared_ptr<MyClass<[...]>>

现场演示在这里。似乎在使用模板模板参数时忽略了 const 限定符,如foo. 有人可以解释一下为什么这不会编译吗?正如预期的那样,调用bar不会导致任何问题。

标签: c++templates

解决方案


是模板推演失败。

没有U和的组合T可以匹配std::shared_ptr<U<T>>from std::shared_ptr<const MyClass<int>>const MyClass不是模板。

你可以超载foo

template <template <class> class U, class T>
void foo(std::shared_ptr<const U<T>> t){ }

template <template <class> class U, class T>
void foo(std::shared_ptr<volatile U<T>> t){ }

template <template <class> class U, class T>
void foo(std::shared_ptr<const volatile U<T>> t){ }

推荐阅读