Reputation: 1411
Title says it all really. Sample code which illustrates the spirit of the affaire:
if( std::is_constructible<T, unsigned long>::value )
{
unsigned long identity = collection.rbegin()->first + 1;
std::shared_ptr<T> newObject(new T(identity));
collection.insert( identity , newObject );
return true;
}
else
{
return false;
}
Upvotes: 1
Views: 231
Reputation: 5618
Since the if
statement can be determined at compile time, I'd expect the compiler to be smart and optimize it directly, just as if you had something like
if ( true ) {
// Some code
}
else {
// Anything here any decent compiler will ignore.
}
Another option is to wrap the behaviour you want in a function, and use std::enable_if
:
template <typename T, typename = typename enable_if<is_constructible<T, int>::value>::type>
bool foo() {
return true;
}
template <typename T, typename = typename enable_if<!is_constructible<T, int>::value>::type>
bool foo() {
return false;
}
// ...
return foo<T>();
Example: http://ideone.com/sgNVr5
Yet another option is to specialize on the boolean value:
template <bool b> bool foo();
template <>
bool foo<true>(){
return true;
}
template <>
bool foo<false>() {
return false;
}
Upvotes: 2
Reputation: 137425
Tag dispatch.
template<class T>
bool foo_impl(std::true_type){
unsigned long identity = collection.rbegin()->first + 1;
std::shared_ptr<T> newObject(new T(identity));
collection.insert( identity , newObject );
return true;
}
template<class T>
bool foo_impl(std::false_type){
return false;
}
template<class T>
bool foo(){
return foo_impl<T>(std::is_constructible<T, unsigned long>());
}
Upvotes: 3