2

Is it possible to deduce the number of constructors a type has during compile time?

#include <iostream>
#include <type_traits>

struct A{

    int m_i;
    float m_f

    //constructor 1
    A(int i): m_i(i) {}

    //constructor 2
    A(float f): m_f(f) {}

};

int main() {

    //prints 2
    std::cout << number_of_constructors<A>::value << '\n';
}  

I was hoping to avoid any macro involvement with the constructors, but perhaps that is the only way.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 7
    First, why do you think the above class has 2 constructors? Second, no. Third, why do you want to know this? – Yakk - Adam Nevraumont May 29 '15 at 20:02
  • I've asked a very similar question a few weeks before, see [here](http://stackoverflow.com/questions/29735942/c-check-whether-constructor-contains-a-parameter-of-given-type). The answer from there is "no". – davidhigh May 29 '15 at 20:02
  • Do you want to know the number of user defined constructors or the total number of constructors? – shuttle87 May 29 '15 at 20:03
  • 1
    Your class has 2 additional implicitly declared constructors, but your program does not make odr-use of them, so they're not defined. Should those two be included in the count, or should they be left out unless they're defined? Anyway, the answer to your question is no, and this sounds like an XY-problem. – Praetorian May 29 '15 at 20:04
  • 5
    how would you count a constructor template, `template A(T&& t) {}`? – davidhigh May 29 '15 at 20:04
  • You could if you had access to all the types defined in your program, a kind of reflection, which is not possible in the latest standard version of C++ (C++14). I wonder what kind of operation this information would allow you to do that overload resolution would not. – edmz May 29 '15 at 20:13
  • @Yakk good point. I neglected to count the constructors added automatically by the compiler. The reason I asked this question, is because I'm writing unit tests for particular classes. I don't want anybody to add another constructor and call it without it first breaking one of my test cases. Someone could easily add a constructor, not write a test for it, and then we run into problems later while seeing that all construction tests have passed. I was also just curious since I knew it was possible to check for the existence of particular constructors. – Trevor Hickey May 29 '15 at 20:25
  • I guess the best I could do in this case is specify a few constructors I think someone might add, and test that they don't exist. – Trevor Hickey May 29 '15 at 20:31

1 Answers1

1

Is it possible to deduce the number of constructors a type has during compile time?

In C++11/14? No, as far i can tell.

Why? Because C++ don't have support for Reflections, but there is now study group SG7: Reflection that will work on proposal that will add reflection to C++.

Andrzej Budzanowski
  • 1,013
  • 11
  • 17