我有以下MWE:
- #include <iostream>
- #include <memory>
- class A {
- public:
- int n = 42;
- typedef std::shared_ptr<A> Ptr;
- };
- template<typename T>
- void foo(typename T::Ptr arg) {
- std::cout << arg->n << std::endl;
- }
- template<typename T>
- void bar(T arg) {
- std::cout << arg.n << std::endl;
- }
- int main() {
- A::Ptr a = A::Ptr(new A());
- foo<A>(a); // Can I avoid giving <A> here explicitly.
- // foo(a); // does not compile
- bar(*a); // after all this does work
- return 0;
- }
对我来说,它似乎也应该可以调用foo(a)而不是foo< A>(a).为什么这不可能,我可以以某种方式改变foo的定义,使之成为可能吗?
我意识到我可以在签名中跳过:: Ptr,但是我仍然希望访问没有指针的A类型.
解决方法
这是不可能的,因为这是不可推理的上下文.
a的类型只是std :: shared_ptr< A>,这意味着如果foo(a)工作,那么以下内容也应该有效:
- std::shared_ptr<A> x(new A());
- foo(x);
如果是这样,那么应该推断什么 – 为什么?你可能会试图说“T应该被推导到A,因为A有一个嵌套的类型Ptr,与std :: shared_ptr< A>”相同.那么,如果有另一个类定义为:
- struct B
- {
- typedef std::shared_ptr<A> Ptr;
- };
应该推断什么? A或B?或者是其他东西?
这是另一个讨论使用不同示例的不可推理上下文的主题:
> C++,template argument can not be deduced
希望有帮助.