C ++构造函数SFINAE

问题描述 投票:4回答:1
#include <iostream>

using namespace std;

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...) : value(1)
    {
       cout <<"ctor unspec  running\n";
    }
};


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


int main()
{
    test<t> h;
}

我试图为创建的对象(constructor)调用第二个h。我不知道为什么会收到此错误:

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...)
     ^~~~

我试图制作整个class t private,但这也没有解决它。我希望第二个constructor运行,即打印`

“ctor unspec running”

我在这里错过了什么?第一次constructor调用应该是SFINAed远,因为typename = decltype(T())不会工作,因为t不能default constructed但我得到一个ambiguous呼叫错误。

c++ c++11 c++14 sfinae
1个回答
5
投票

SFINAE只发生在紧急情况下。由于T是类的模板参数而不是函数的模板参数,因此它不是直接上下文。这意味着它成为一个“硬”错误。这是一个很难的错误,因为无论你发送给构造函数的模板参数的是什么参数,它总是会出错。

一个解决方案是添加一个等于T的模板参数,并用它来制作SFINAE:

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

由于U是直接背景,因此SFINAE适用于此。

使用SFINAE,没有订购。每个匹配函数都是“相等”,这意味着如果有多个匹配函数,则没有“更好”的函数,因为它是受约束的。所以用相反的约束来限制另一个是一个好主意:

template <typename... Args, typename U = T,
    std::enable_if_t<!std::is_default_constructible<U>::value>* = nullptr>
test(Args...) : value(1)
{
   cout <<"ctor unspec  running\n";
}

Live example

© www.soinside.com 2019 - 2024. All rights reserved.