C ++:根据参数实例化一个模板类 [英] C++: instantiate a templated class according to an argument
问题描述
我经常发现需要使用以下模式:
template< typename T&
class SomeClass:public Base {
SomeClass(const T& t){...}
...
};
template< typename T>
SomeClass< T> * makeSomeClass(const T& t){
return new SomeClass T(t);
}
并使用它:
Base * = makeSomeClass(123);
当我不想明确指定 T
因为它是一个非常复杂(函数类型,等等)和函数参数可以推断类型隐式。
有没有办法做到没有额外的make函数?为什么模板扣除只在函数参数中工作,而不是在构造函数中?
不,没有办法一个额外的make函数。
它不能使用构造函数的原因是因为它将是可笑的复杂。考虑这个:
template< typename T>
struct Foo
{
Foo(const T& val){...}
Foo(const Foo< T>& other){...} // Copy构造函数
};
Foo< int> X;
如果我随后调用:
Foo(x);
这给我一个 Foo < Foo< int> >
或者我为 Foo
?
调用复制构造函数>
请注意,您可以使用模板模板自动创建make函数:
/ p> 模板< template< typename> class TemplateClass,typename Type>
TemplateClass< Type> make(const Type& x)
{
return TemplateClass< Type>(x);
}
然后您可以使用:
make< SomeClass>(123); //返回SomeClass< int>
I often find the need to use the following pattern:
template<typename T>
class SomeClass : public Base {
SomeClass(const T& t) {...}
...
};
template<typename T>
SomeClass<T>* makeSomeClass(const T& t) {
return new SomeClass<T>(t);
}
And to use it:
Base* = makeSomeClass(123);
This is useful when I don't want to explicitly specify T
because it is a very complex (function types, etc') and the function argument can deduce the type implicitly.
Is there a way to do this without the extra "make" function? Why does template deduction work only in function arguments and not in constructor arguments?
No, there is no way to do this without an extra make function.
The reason it doesn't work with constructors is because it would be ridiculously complicated. Consider this:
template <typename T>
struct Foo
{
Foo(const T& val) { ... }
Foo(const Foo<T>& other) { ... } // Copy constructor
};
Foo<int> x;
What if I then call:
Foo(x);
Does that give me a Foo< Foo<int> >
or am I calling the copy constructor for a Foo<int>
?
It would be ambiguous in too many places, so the extra function is necessary.
Note that you can automate the create of make functions a little by using template templates:
template <template <typename> class TemplateClass, typename Type>
TemplateClass<Type> make(const Type& x)
{
return TemplateClass<Type>(x);
}
Then you can use:
make<SomeClass>(123); // returns a SomeClass<int>
这篇关于C ++:根据参数实例化一个模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!