问题
Possible Duplicate:
Can the template parameters of a constructor be explicitly specified?
following up on my previous question, (I found this situation in edit 2)
Laid out simple in code:
#include <iostream>
struct Printer
{
Printer() { std::cout << "secret code" << std::endl; }
};
template <class A>
struct Class
{
template <class B, class C>
Class(B arg)
{
C c; /* the 'secret code' should come from here */
std::cout << arg << std::endl;
}
Class(double arg) { std::cout << "double" << std::endl; }
Class(float arg) { std::cout << "float" << std::endl; }
/* this forbids the use of printer in the first parameter */
Class(Printer printer) { throw std::exception(); /* here be dragons */ }
};
int main()
{
Class<int> c(1.0f);
Class<int>* ptr = new Class<int>((double)2.0f);
return 0;
}
// Can anyone print 'secret code' while creating an object of type 'Class' ?
Detailed: For a template constructor, can you specify a template argument which is not part of the constructor's arguments when an object get's instantiated?
I think this deserves a question of its own.
回答1:
No, it's not possible.
There is no syntax with which you can provide explicit template parameters to a constructor template. You can only provide explicit template parameters for the class template as a whole.
The following text from [temp.arg.explicit] (2003 wording, 14.8.1/5) covers the scenario. Though the clause is non-normative, it serves to explain to us that, as an inherent restriction of the grammar, this is not possible:
Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.
This, partially, comes out of the fact that you never actually invoke the constructor explicitly yourself. When you write, say, A() you are not calling the constructor like a function, even though it looks as if you are ("conversion member function templates and constructor member function templates are called without using a function name").
回答2:
I think he want to know how to instantiate this class with C as SomeType:
template<typename A>
class foo
{
template<typename B, typename C>
foo(B b)
{
C c;
}
};
I don't know if this is possible.
来源:https://stackoverflow.com/questions/6358882/template-constructor-weirdness