私は次のコードを調べていました(実際のアプリケーションはなく、好奇心からです)。
#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
は問題を引き起こしません。
テンプレート推論の失敗です。
のない組み合わせもありませんU
し、T
一致するstd::shared_ptr<U<T>>
からで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){ }
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加