lundi 6 avril 2015

Conditional compilation of templates

I am trying to get static_assert to help me avoid null pointers in C++11.


The problem seems to be that C++11 require the compiler to compile templates even if they are not instantiated.


I have the following code:



#include <type_traits>

template<typename T, typename... Us>
std::enable_if_t< std::is_constructible<T, Us...>::value == true, T * >
create_if_constructible(Us... args) { return new T(args...); }

template<typename T, typename... Us>
std::enable_if_t< std::is_constructible<T, Us...>::value == false, T * >
create_if_constructible(Us... args) {
static_assert( false, "Class T constructor does not match argument list.");
return nullptr;
}

struct ClassA {
ClassA(int a, string b) {}
};

void foo() {
ClassA *a = create_if_constructible<ClassA>(1, "Hello");
// ClassA *b = create_if_constructible<ClassA>(1, "Hello", "world"); // I want compile time error here.
}


I would like this to compile without error. But the static_assert is compiled and gives me a compile time error.


Only if the the second instantiation of the ClassA is in the code should it give me a compile time error.


Aucun commentaire:

Enregistrer un commentaire