[英]Partially avoid class template parameter (deduce from constructor argument)
is there a way to avoid specifying a class template parameter if the type is being used in the constructor's argument?如果在构造函数的参数中使用了类型,有没有办法避免指定 class 模板参数?
I have:我有:
template< typename T, typename X >
class myclass {
myclass( typename X ) {};
X myfunct() { return X(); };
};
so is there some design pattern to make it possible to instantiate myclass using just那么是否有一些设计模式可以仅使用实例化 myclass
myclass< TType > myclass_object( x_object );
instead of代替
myclass< TType, XType > myclass_object( x_object );
Thanks to you template programming experts, this stuff sometimes really freaks me out.感谢您的模板编程专家,这些东西有时真的把我吓坏了。
Edit: added function with X return type to make situation clearer.编辑:添加了带有 X 返回类型的 function 以使情况更清晰。
Only if you don't need to know the second type for the rest of your class.仅当您不需要知道 class 的 rest 的第二种类型时。
template< typename T >
class myclass {
template < typename X >
myclass( typename X ) {};
};
This works because the second template is a function, and for functions the compiler will deduce the template arguments from the types of the regular arguments if it can.这是因为第二个模板是 function,对于函数,如果可以的话,编译器将从常规 arguments 的类型中推导出模板 arguments。 In this case it can.
在这种情况下可以。
Use a helper function that deduces the argument types and explicitly specifies the class instantiation.使用帮助器 function 推断参数类型并显式指定 class 实例化。 See
std::make_pair
for an example.有关示例,请参见
std::make_pair
。
Sort answer: no.排序答案:没有。
myclass<X>
and myclass<Y>
cannot be deduced by construction from Z
because Z
might convert to either X
or Y
. myclass<X>
和myclass<Y>
不能从Z
构造推导,因为Z
可能转换为X
或Y
。
myclass<int> x (123);
myclass<float> x (123);
You need a helper function or a complete type.你需要一个助手 function 或一个完整的类型。
template <typename T> myclass<T> make_myclass (const T &);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.