I have a template function that I expect to be templatized for different types at different places.
The problem is that I would like to know at compile time if there is an specialization for the given type to generate in 2 different ways another template.template<typename T>
bool tobool(const T&){ throw Exception("Can't cast to bool");};
template<> bool tobool<bool>(const bool &value){ return val开发者_如何学Goue;}
I know you can test for function existance like in here.
Any chance on how to test if tobool has been specialized?
Imagine that I want to generate a isbool() that returns true if tobool() has been specialized and returns false if not.
As a (somewhat ugly and brittle) workaround, you could require specialization of a struct rather than a function and include a class constant to indicate whether the struct has been specialized:
template <typename T>
struct ToBool {
static bool tobool(const T&);
static const bool specialized = false;
};
Another option is to only define tobool
in specializations. That way, ToBool<Foo>::tobool(f)
won't compile for any classes Foo
that ToBool
hasn't been specialized for.
As an alternative to tobool
, you can use explicit conversion operators if you have control over the classes to be converted.
class Foo {
public:
operator bool();
...
};
...
Foo f;
if (f) ...
If the type doesn't have a bool conversion (well, a conversion to a numeric or pointer type, both of which have standard conversions to bool), the program won't compile. Voila, compile time checking for a conversion.
If you don't want implicit conversion to bool, you can define an operator! and use a double-bang for explicit conversion (though this isn't as readable):
class Foo {
public:
bool operator!();
...
};
...
Foo f;
if (!!f) ...
The answer to your specific question is this: No, you cannot check whether T is using the primary or the specialized template. @Martin York's question is a very good one: why on earth would you want to check that? :)
精彩评论