Reputation: 238
I have a template class with a constructor that takes a std::vector<T>
. For every object except one I want it to make operation A. But for that one object, I want it to do some other stuff B.
Is there a possibility to create an explicit instantiation of only the constructor for a template class? I hope its described precisely enough.
Regards
Update: I have now implemented a test case:
//header
Container(const std::vector<T>& source)
{...}
//source code
template <> Container<int>::Container(const std::vector<int>& source)
{
throw 42;
}
This example compiles but doesn't work. I export this into a dll and want to have it being called whenever I try to create an instance of the class with generic parameter int. But as it is now, it only calls the standard constructor used for every other object. Is there a change I have to make to the declaration?
Update: I succeeded! Just had to copy it to the header file.
Update: OK, now I have another problem. I am able to make a specialization for 'simple' types but not for templates. I tried it this way:
template<typename T>
Container<MyClass<T>>::Container(const std::vecror<MyClass<T>>& source)
{...}
I want to specialize it for every MyClass object, but MyClass itself shall be able to live on as a template.
Upvotes: 0
Views: 520
Reputation: 64293
If I understood your question correctly, you want to do this :
template< typename T >
struct A
{
template< typename P >
A( std::vector< P > &v )
{
}
};
Upvotes: 0
Reputation: 272802
Your question isn't clear. Perhaps you mean something like the following?
template <typename T>
class Foo
{
public:
Foo() { std::cout << "standard" << std::endl; }
};
template <>
Foo<float>::Foo() { std::cout << "random" << std::endl; } // Special case
...
Foo<int> f1; // Prints "standard"
Foo<float> f2; // Prints "random"
Upvotes: 5
Reputation: 5805
There is no way to do explicit constructor template instantiation -- this was covered here: C++ invoke explicit template constructor
Upvotes: 0
Reputation: 4191
Which compiler?
I have had trouble with template instanciation with some old version of g++ compiler and with Solaris and HPUX c++ compiler.
The template <>
is used to specify explicit instanciation.
It is a long time I do not have specialized only a method of a class.
Did you try ?
template <> TemplateClass<InstanciedType>::TemplateClass() {
...
}
Where TemplateClass is the template class instanciation you want to override.
Upvotes: 0