jeudi 21 décembre 2017

C++ constructor SFINAE

#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

template <typename T>
struct WhichType;

template <typename T>
class test
{

    public:
    T value;

    template <typename... Args, typename = decltype(T())>
    test(Args... args): value(args...)
    {
       cout <<"ctor running\n";
    }

    template <typename... Args>
    test(Args... args)
    {
       cout <<"ctor unspec  running\n";
    }
};


class t
{
    public:
    t() = delete;
    //explicit t(int) {}


};


int main()
{

    //test<vector<int>> f(1,2);

    test<t> h; // should call 2nd ctor but doesnt Y 



}

I am trying to call the second constructor for the object created (h). I do not know why I get this error:

prog.cc: In function 'int main()':
prog.cc:45:13: error: call of overloaded 'test()' is ambiguous
     test<t> h;
             ^
prog.cc:25:5: note: candidate: 'test<T>::test(Args ...) [with Args = {}; T = t]'
     test(Args... args)
     ^~~~
prog.cc:19:5: note: candidate: 'test<T>::test(Args ...) [with Args = {}; <template-parameter-2-2> = t; T = t]'
     test(Args... args): value(args...)
     ^~~~

I tried to make the entire class t private but that did not fix it either. I want the second constructor to run i.e. print `

"ctor unspec running"

What am I missing here? The first constructor call should be SFINAed away since typename = decltype(T()) wont work as t can not be default constructed but instead I get an ambiguous call error.

Aucun commentaire:

Enregistrer un commentaire