Define member typedef based on which constructor is used

105 Views Asked by At

Is there a way to have a member typedef based on which constructor is used?

For example, in the below code, if ctor #1 is used then Type should be const T, while if ctor #2 is used then the Type should be T.

#include <iostream>
#include <type_traits>

template<typename T>
struct C
{
    using Type = /*I want this Type to be based on which ctor is used*/

    C(void (*ptr)(T))       //#1 if this ctor is used then Type should be say "const T"
    {
        
    }
  
    C(T)                   //#2 if this ctor is used then Type should be say "T"
    {

    }    
};

void func(int);
int main() {
    C c1(&func);    //Type should be const int
    C c2(4);        //Type should be int    
}
1

There are 1 best solutions below

0
Etienne Laurin On BEST ANSWER

Template deduction guides can be used to control the type returned by a constructor. For example:

template<typename T>
struct C {
    using Type = T;
    C(void (*ptr)(T)){}  
    C(T){}
};

template <typename T> C(void (*)(T)) -> C<const T>;
template <typename T> C(T) -> C<T>;