Reputation:
In the code below, I am trying to check the signature of the class that is passed as the second template argument to WTrajectory
. In the current implementation, the constructor of WTrajectory
compares the types of the template argument T
and the template argument of the type that is passed to it as the second argument.
The current implementation can perform the check. However, I would prefer to perform it at compile time, if it is possible. Moreover, I would also like to check if the template argument TWPoint
has a member function returnTimeTypeID
, also at compile time (a solution that performs this check at run time can be found here: link).
template<typename T>
struct WPoint
{
const std::type_info& returnTimeTypeID(void) const
{return typeid(T);}
};
template<typename T, typename TWPoint>
struct WTrajectory
{
WTrajectory(const TWPoint& wp)
{
compare_types(wp);
}
void compare_types(const TWPoint& wp)
{
if (typeid(T) != wp.returnTimeTypeID())
throw std::runtime_error("Error");
}
};
Upvotes: 0
Views: 387
Reputation: 2250
If WPoint
contains more than just the type info, then the following code will work
template<typename T>
struct WPoint
{
// ... stuff not related to type checking
};
template<typename T>
struct WTrajectory
{
WTrajectory(const WPoint<T>& wp)
{
}
};
You could remove WPoint
if it does not contain anything else besides the type info.
Upvotes: 0
Reputation: 96281
Since returnTimeTypeID
is non-virtual the compiler will know the dynamic type of TWPoint
at compile time. So instead of doing a runtime check just change your template:
template<typename T>
struct WTrajectory
{
typedef T TWPoint;
...
The best way to check whether a template type has a perticular method at compile time is to just call the method. You'll get a compilation error if it doesn't provide the needed functionality.
Upvotes: 1